Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Retrieve Top AND Bottom Values R Dataframe

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)) )
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading