Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I sort one vector based on values of another

Tags:

sorting

r

what about this one

x[order(match(x,y))]

You could convert x into an ordered factor:

x.factor <- factor(x, levels = y, ordered=TRUE)
sort(x)
sort(x.factor)

Obviously, changing your numbers into factors can radically change the way code downstream reacts to x. But since you didn't give us any context about what happens next, I thought I would suggest this as an option.


How about?:

rep(y,table(x)[as.character(y)])

(Ian's is probably still better)


In case you need to get order on "y" no matter if it's numbers or characters:

x[order(ordered(x, levels = y))]
4 4 4 2 2 1 3 3 3

By steps:

a <- ordered(x, levels = y) # Create ordered factor from "x" upon order in "y".
[1] 2 2 3 4 1 4 4 3 3
Levels: 4 < 2 < 1 < 3

b <- order(a) # Define "x" order that match to order in "y".
[1] 4 6 7 1 2 5 3 8 9

x[b] # Reorder "x" according to order in "y".
[1] 4 4 4 2 2 1 3 3 3