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
谢谢
最佳答案
不是真的涉及 top_n()
,但你可以尝试:
df %>%
arrange(x) %>%
slice(c(1, n()))
x
1 1
2 10
或者:
df %>%
slice(which(x == max(x) | x == min(x))) %>%
distinct()
或者(由@Gregor 提供):
df %>%
slice(c(which.min(x), which.max(x)))
关于r - Top_n 返回最大值和最小值 - R,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59887497/