The order function in R

Asked

Viewed 1,619 times

11

I don’t understand what happens. Watch

> 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 don’t understand why vector x is not ordered. Note, when I give order(x) add the 7

And in this case? Supposedly you wouldn’t have to give me vector x ordered downwards?

> order(x, decreasing=TRUE)

[1] 5 6 4 2 1 3

What a strange thing! Help please

1 answer

12


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

Thus, to get back the vectorx ordered, 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 to you 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
  • 1

    Thank you very much... now I understand

  • 1

    @Vasco for nothing! If the answer answered your question, you can accept it, abs!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.