Skip to content

R: how to sort a vector according to another

As usual, it’s always what seems to be the simplest operations which turn out the hardest to implement in R (although usually once you’ve figured it out it’s a one-liner or something ;)). Sorting a vector based on the values of another vector is no exception to this.
There is a nice post on stackoverflow on how sort a vector so that values are reorganized in a specified order (that order being specified via another vector), here I just wanted to sort vector x according to the order of values in vector y. It took a bit of thinking, but once it’s been sorted out I think the code is pretty self-explanatory (and if it’s not, just run it step by step to make it easier):

> set.seed(1);
> x=runif(10);
> x;
[1] 0.26550866 0.37212390 0.57285336 0.90820779 0.20168193 0.89838968 0.94467527 0.66079779 0.62911404 0.06178627
> y=(10:1)*2;
> y;
[1] 20 18 16 14 12 10 8 6 4 2
> x[order(y)]
[1] 0.06178627 0.62911404 0.66079779 0.94467527 0.89838968 0.20168193 0.90820779 0.57285336 0.37212390 0.26550866

As a bonus, not that sort(x) and x[order(x)] give equivalent results.

Posted in R (R-project).

0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

Some HTML is OK

or, reply to this post via trackback.

Sorry about the CAPTCHA that requires JS. If you really don't want to enable JS and still want to comment, you can send me your comment via e-mail and I'll post it for you.

Please solve the CAPTCHA below in order to fight spamWordPress CAPTCHA