R的排名和顺序

Ale*_*lex 43 sorting r

我无法理解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
Run Code Online (Sandbox Code Playgroud)

有人可以为我阐明这个吗?谢谢

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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

  • 当有关系时也要注意区别. (4认同)

gen*_*ama 9

我总是觉得考虑两者之间的区别让人感到困惑,我一直认为,"我怎样才能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
Run Code Online (Sandbox Code Playgroud)


Ale*_*lex 6

事实证明,这是一个特例,使事情变得混乱。我在下面为有兴趣的任何人解释:

rank 返回升序列表中每个元素的顺序

order 返回每个元素在升序列表中的索引


小智 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
Run Code Online (Sandbox Code Playgroud)


小智 6

用外行人的语言来说,order在对值进行排序后给出值的实际位置/位置 例如:

a<-c(3,4,2,7,8,5,1,6)
sort(a) [1] 1 2 3 4 5 6 7 8
Run Code Online (Sandbox Code Playgroud)

1in的位置a是 7。类似地,2in的位置a是 3。

order(a) [1] 7 3 1 2 6 8 4 5
Run Code Online (Sandbox Code Playgroud)

  • 但问题是关于“等级”和“顺序”之间的区别。 (2认同)