top_n versus order in r

后端 未结 2 971
爱一瞬间的悲伤
爱一瞬间的悲伤 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: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).

提交回复
热议问题