Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Top_n return both max and min value - R

Tags:

r

dplyr

top-n

is it possible for the top_n() command to return both max and min value at the same time?

Using the example from the reference page https://dplyr.tidyverse.org/reference/top_n.html

I tried the following

df <- data.frame(x = c(10, 4, 1, 6, 3, 1, 1)) 
df %>% top_n(c(1,-1)) ## returns an error

df <- data.frame(x = c(10, 4, 1, 6, 3, 1, 1)) 
df %>% top_n(1) %>%  top_n(-1) ## returns only max value

Thanks

like image 410
Yaahtzeck Avatar asked Dec 17 '22 14:12

Yaahtzeck


1 Answers

Not really involving top_n(), but you can try:

df %>%
 arrange(x) %>%
 slice(c(1, n()))

   x
1  1
2 10

Or:

df %>%
 slice(which(x == max(x) | x == min(x))) %>%
 distinct()

Or (provided by @Gregor):

df %>%
 slice(c(which.min(x), which.max(x)))

Or using filter():

df %>%
 filter(x %in% range(x) & !duplicated(x))
like image 145
tmfmnk Avatar answered Feb 01 '23 09:02

tmfmnk