r - Sort vector of integers in specific (custom) order -


i have vector of integers let's 1 3 (can more):

x <- sample(1:3, 10, replace=t)  [1] 1 3 1 2 2 1 3 2 3 2 

if sort x i'll get

sort(x) [1] 1 1 1 2 2 2 2 3 3 3 

but need 2s go first, 1s, 3s.

[1] 2 2 2 2 1 1 1 3 3 3 

so, if have vector y = c(2, 1, 3), how can use sorting order?

and need not values itself, index of sorted values in original vector, order function.

a simple remapping of values works:

x <- sample(1:3, 10, replace=t) x  [1] 2 3 1 1 3 2 2 3 3 2 order(c(2,1,3)[x])  [1]  1  6  7 10  3  4  2  5  8  9 

Comments