Dfuller
Dfuller

Reputation: 19

How can I sort a vector based on the indices contained in a different vector?

I have a vector that I would like to sort based on the indices contained in another vector. For instance, if I have these vectors:

 x <- c(0.4, 0.8, 0.1, 0.2) #<--values to be sorted
 y <- c(3,1,4,2)# <--indices to base the sorting

Vector y will always have distinct values from 1 to the length of x (and therefore, both vectors will always have the same number of elements)

The expected vector would be:

 0.8,0.2,0.4,0.1

Upvotes: 1

Views: 54

Answers (2)

David Arenburg
David Arenburg

Reputation: 92300

Or use order

x[order(y)]
## [1] 0.8 0.2 0.4 0.1

Upvotes: 3

lukeA
lukeA

Reputation: 54277

Try rev(x[y]) to get your expected output.

Upvotes: 1

Related Questions