Home > Software design >  Retrieve Top AND Bottom Values R Dataframe
Retrieve Top AND Bottom Values R Dataframe

Time:11-09

Looking for a way to select the top 3 AND bottom 3 rows by value. I have tried using slice_max() in conjunction with slice_min() with no success.

id  value
a  0.9
b  0.2
c -0.4
d -0.9
e  0.6
f  0.8
g -0.3
h  0.1
i  0.2
j  0.5
k -0.2

# Desired output: <br>
a  0.9
f  0.8
e  0.6
d -0.9
c -0.4
g -0.3

CodePudding user response:

dplyr

dat %>%
  filter(!between(dense_rank(value), 4, n() - 4))
#   id value
# 1  a   0.9
# 2  c  -0.4
# 3  d  -0.9
# 4  e   0.6
# 5  f   0.8
# 6  g  -0.3

or

dat %>%
  arrange(value) %>%
  slice( unique(c(1:3, n() - 0:2)) )
  • Related