Search code examples
rdplyrtop-n

Top_n return both max and min value - R


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


Solution

  • 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))