我有一个向量,可以返回最高和最低值,但如何返回前五个最高值?是否有简单的一行代码解决方案?
> a <- c(1:100)
> tail(sort(a),5)
[1] 96 97 98 99 100
x[order(x)[1:5]]
x[order(x, decreasing = TRUE)[1:5]]
,但是被接受的答案也不错。 - kennyB是的,head( X, 5)
其中 X
是您排序后的向量。
tail(sort.int(x, partial=length(x) - 4), 5)
> 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
head(sort(a, decreasing=TRUE), 5)
可以将向量a按从大到小的顺序排序,并返回前5个最大的值。 - Marek