How to return 5 topmost values from vector in R?

2019-01-11 13:02发布

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?

标签: r vector topmost
4条回答
SAY GOODBYE
2楼-- · 2019-01-11 13:15
> a <- c(1:100)
> tail(sort(a),5)
[1]  96  97  98  99 100
查看更多
劳资没心,怎么记你
3楼-- · 2019-01-11 13:15
x[order(x)[1:5]]
查看更多
不美不萌又怎样
4楼-- · 2019-01-11 13:20

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

查看更多
The star\"
5楼-- · 2019-01-11 13:24
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 
查看更多
登录 后发表回答