我无法理解R函数rank和R函数之间的区别order.他们似乎产生相同的输出:
> rank(c(10,30,20,50,40))
[1] 1 3 2 5 4
> order(c(10,30,20,50,40))
[1] 1 3 2 5 4
有人可以为我阐明这个吗?谢谢
Jus*_*tin 62
> set.seed(1)
> x <- sample(1:50, 30)    
> x
 [1] 14 19 28 43 10 41 42 29 27  3  9  7 44 15 48 18 25 33 13 34 47 39 49  4 30 46  1 40 20  8
> rank(x)
 [1]  9 12 16 25  7 23 24 17 15  2  6  4 26 10 29 11 14 19  8 20 28 21 30  3 18 27  1 22 13  5
> order(x)
 [1] 27 10 24 12 30 11  5 19  1 14 16  2 29 17  9  3  8 25 18 20 22 28  6  7  4 13 26 21 15 23
rank返回具有每个值的"rank"的向量.第一个位置的数字是第9个最低位.order返回将初始向量x按顺序排列的索引.
第27个值x是最低的,所以27是第一个元素order(x)- 如果你看rank(x),第27个元素是1.
> x[order(x)]
 [1]  1  3  4  7  8  9 10 13 14 15 18 19 20 25 27 28 29 30 33 34 39 40 41 42 43 44 46 47 48 49
我总是觉得考虑两者之间的区别让人感到困惑,我一直认为,"我怎样才能order使用rank"?
从贾斯汀的例子开始:
## Setup example to match Justin's example
set.seed(1)
x <- sample(1:50, 30) 
## Make a vector to store the sorted x values
xx = integer(length(x))
## i is the index, ir is the ith "rank" value
i = 0
for(ir in rank(x)){
    i = i + 1
    xx[ir] = x[i]
}
all(xx==x[order(x)])
[1] TRUE
小智 6
rank 是一个索引(整数)更复杂,而不是必须的:
> rank(c(1))
[1] 1
> rank(c(1,1))
[1] 1.5 1.5
> rank(c(1,1,1))
[1] 2 2 2
> rank(c(1,1,1,1))
[1] 2.5 2.5 2.5 2.5
小智 6
用外行人的语言来说,order在对值进行排序后给出值的实际位置/位置 例如:
a<-c(3,4,2,7,8,5,1,6)
sort(a) [1] 1 2 3 4 5 6 7 8
1in的位置a是 7。类似地,2in的位置a是 3。
order(a) [1] 7 3 1 2 6 8 4 5