How to return 5 topmost values from vector in R?

故事扮演 提交于 2019-12-17 10:56:19

问题


I have a vector and I'm able to return highest and lowest value, but how to return 5 topmost values? Is there a simple one-line solution for this?


回答1:


> a <- c(1:100)
> tail(sort(a),5)
[1]  96  97  98  99 100



回答2:


x[order(x)[1:5]]



回答3:


Yes, head( X, 5) where X is your sorted vector.




回答4:


tail(sort.int(x, partial=length(x) - 4), 5)

Using sort.int with partial has the advantage of being (potentially) faster by (potentially) not doing a full sort. But in reality, my implementation appears a little slower. Maybe this is because with parameter partial != NULL, shell sort is used rather than quick sort?

> x <- 1:1e6
> system.time(replicate(100, tail(sort.int(x, partial=length(x) - 4), 5)))
   user  system elapsed 
  4.782   0.846   5.668
> system.time(replicate(100, tail(sort(x), 5)))
   user  system elapsed 
  3.643   0.879   4.854 


来源:https://stackoverflow.com/questions/3692563/how-to-return-5-topmost-values-from-vector-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!