理解 order() 函数 [英] Understanding the order() function
问题描述
我正在尝试了解 order()
函数的工作原理.我的印象是它返回了一个索引排列,当排序时,会对原始向量进行排序.
I'm trying to understand how the order()
function works. I was under the impression that it returned a permutation of indices, which when sorted, would sort the original vector.
例如
> a <- c(45,50,10,96)
> order(a)
[1] 3 1 2 4
我原以为这会返回 c(2, 3, 1, 4)
,因为排序的列表将是 10 45 50 96.
I would have expected this to return c(2, 3, 1, 4)
, since the list sorted would be 10 45 50 96.
谁能帮我理解这个函数的返回值?
Can someone help me understand the return value of this function?
推荐答案
这似乎可以解释它.
order
的定义是 a[order(a)]
在递增顺序.这适用于您的示例,其中正确顺序是第四个,第二个,第一个,然后是第三个元素.
The definition of
order
is thata[order(a)]
is in increasing order. This works with your example, where the correct order is the fourth, second, first, then third element.
您可能一直在寻找 rank
,它返回元素
<代码>R>a <- c(4.1, 3.2, 6.1, 3.1)
<代码>R>订单(一)[1] 4 2 1 3
<代码>R>排名(a)[1] 3 2 4 1
所以 rank
告诉你数字的顺序,order
告诉您如何按升序获取它们.
You may have been looking for rank
, which returns the rank of the
elements
R> a <- c(4.1, 3.2, 6.1, 3.1)
R> order(a)
[1] 4 2 1 3
R> rank(a)
[1] 3 2 4 1
so rank
tells you what order the numbers are in,
order
tells you how to get them in ascending order.
plot(a, rank(a)/length(a))
将给出 CDF 的图形.看看为什么order
很有用,不过,试试 plot(a, rank(a)/length(a),type="S")
这让人一团糟,因为数据不是按升序排列的
plot(a, rank(a)/length(a))
will give a graph of the CDF. To see why
order
is useful, though, try plot(a, rank(a)/length(a),type="S")
which gives a mess, because the data are not in increasing order
如果你这样做了oo<-order(a)
plot(a[oo],rank(a[oo])/length(a),type="S")
或者干脆oo<-order(a)
plot(a[oo],(1:length(a))/length(a)),type="S")
您将获得 CDF 的折线图.
If you did
oo<-order(a)
plot(a[oo],rank(a[oo])/length(a),type="S")
or simply
oo<-order(a)
plot(a[oo],(1:length(a))/length(a)),type="S")
you get a line graph of the CDF.
我敢打赌你在考虑排名.
I'll bet you're thinking of rank.
这篇关于理解 order() 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!