Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort vector of integers in specific (custom) order

Tags:

sorting

r

vector

I have a vector of integers let's say from 1 to 3 (can be more):

x <- sample(1:3, 10, replace=T)

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

If I sort x I'll get

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

But I need 2s to go first, then 1s, then 3s.

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

So, if I have a vector y = c(2, 1, 3), how I can use it for sorting order?

And actually I need not the values itself, but the index of sorted values in original vector, as I get from order function.

like image 740
yuk Avatar asked Jul 19 '13 17:07

yuk


1 Answers

A somewhat convoluted option:

x[order(factor(x,levels = c(2,1,3)))]

or obviously, just the order call for just the indices.

like image 116
joran Avatar answered Sep 19 '22 07:09

joran