Top_n 返回最大值和最小值 - R

Yaa*_*eck 4 r top-n dplyr

top_n() 命令是否可以同时返回最大值和最小值?

使用参考页面https://dplyr.tidyverse.org/reference/top_n.html 中的示例

我尝试了以下

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

Run Code Online (Sandbox Code Playgroud)

谢谢

tmf*_*mnk 5

不是真的涉及top_n(),但你可以尝试:

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

   x
1  1
2 10
Run Code Online (Sandbox Code Playgroud)

或者:

df %>%
 slice(which(x == max(x) | x == min(x))) %>%
 distinct()
Run Code Online (Sandbox Code Playgroud)

或者(由@Gregor 提供):

df %>%
 slice(c(which.min(x), which.max(x)))
Run Code Online (Sandbox Code Playgroud)

  • 类似地,“df %&gt;% slice(which.max(x),which.min(x))”意味着您不需要“distinct”。(尽管它没有给你省略“distinct”的选项) (2认同)