The order function in R

10

I do not understand what happens. Please note

> x<-c(-2,4,-6,5,9,7)

> x

[1] -2  4 -6  5  9  7

> order(x)

[1] 3 1 2 4 6 5

I do not understand why the x-vector is not ordered. Look, when I give order(x) add 7

And in this case? Supposedly you would not have to give me the vector x sorted in decreasing order?

> order(x, decreasing=TRUE)

[1] 5 6 4 2 1 3

How strange! Help please

    
asked by anonymous 18.04.2014 / 18:43

1 answer

12

The function order does not return the original ordered vector, but returns a vector with the positions so that x is in ascending order.

So, to get back the x pended vector, you have to put x[order(x)] :

x[order(x)]
[1] -6 -2  4  5  7  9

Or, in descending order:

x[order(x, decreasing=TRUE)]
[1]  9  7  5  4 -2 -6

If you want to do this directly, you can use the function sort , which already returns the ordered vector instead of the positions:

sort(x)
[1] -6 -2  4  5  7  9

Or:

sort(x, decreasing=TRUE)
[1]  9  7  5  4 -2 -6
    
18.04.2014 / 20:23