top_n versus order in r

后端 未结 2 972
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-18 21:47

I am having trouble understanding the output from dplyr\'s top_n function. Can anybody help?

n=10

df = data.frame(ref=sample(letters,n),score=rnorm(n))

req         


        
相关标签:
2条回答
  • 2021-01-18 22:24

    My misunderstanding and expectation was due to my reading of the documentation linked to in the question and described in the comments. Despite some documentation claims, top_n does not generated output ordered by wt.

    0 讨论(0)
  • 2021-01-18 22:31

    Both outputs are the same, but top_n is not rearranging the rows.

    You can get the same result as df[order(df$score,decreasing = T)[1:5],] using arrange()

    top_n(df, 5, score) %>% arrange(desc(score))
    

    Flipping the ordering around, df[order(df$score,decreasing = F)[1:5],] is equivalent to top_n(df, -5, score) %>% arrange(score).

    0 讨论(0)
提交回复
热议问题