Home > Software engineering >  Sort function in R when index.return=TRUE
Sort function in R when index.return=TRUE

Time:12-12

I have the following vector in R:

> A<-c(8.1915935,  3.0138083,  0.3245712, 10.7353747, 13.7505131 ,63.2337407, 16.7505131,  5.7781297)

I want to sort it, and, at the same time, know each element's position in the sorted vector. So i use the following function:

sort(A, index.return=T)

And I get the following output, which I don't clearly understand:

$x
[1]  0.3245712  3.0138083  5.7781297  8.1915935 10.7353747 13.7505131 16.7505131 63.2337407

$ix
[1] 3 2 8 1 4 5 7 6

Looking at the original vector A, the first element, goes in the 4th position of the sorted vector. So the first element of "$ix" should be 4. Why is it 3?

Then, the biggest number of the vector is the 6th of A. But the 6th element of $ix is not 8, as I expected to see (the length of the vector)but 6. Why?

And so on, for all the elements. Clearly, there is something I don't understand about this output.

CodePudding user response:

$ix is indicating the position of the elements of x in the original vector; you were hoping for the reverse -- the location of the elements in the original vector in x. The difference is between order() and rank()

> order(A)
[1] 3 2 8 1 4 5 7 6
> rank(A)
[1] 4 2 1 5 6 8 7 3
  • Related