我不太理解 dplyr 的 top_n 函数的输出。有人可以帮忙吗?
n=10
df = data.frame(ref=sample(letters,n),score=rnorm(n))
require(dplyr)
print(dplyr::top_n(df,5,score))
print(df[order(df$score,decreasing = T)[1:5],])
top_n
的输出结果不像我预期的那样按照分数进行排序。与使用 order
函数相比较。
ref score 1 i 0.71556494 2 p 0.04463846 3 v 0.37290990 4 g 1.53206194 5 f 0.86307107 ref score 7 g 1.53206194 10 f 0.86307107 1 i 0.71556494 6 v 0.37290990 4 p 0.04463846我阅读的文档也暗示了
top_n
结果应该按照指定的列排序,例如:
https://www.rstudio.com/wp-content/uploads/2015/02/data-wrangling-cheatsheet.pdf
top_n
后,原始顺序中仅保留了5行。尝试:df %>% top_n(5) %>% arrange(desc(score))
- agenistop_n
相当于filter(x, min_rank(desc(wt)) <= n)
,不会对行进行排序,文档也没有建议这样做。 - Axemanwt
上使用min_rank
。我同意 cheatsheet 在这方面是错误的。 - Axeman