I have a vector x, that I would like to sort based on the order of values in vector y. The two vectors are not of the same length.
x <- c(2, 2, 3, 4, 1, 4, 4, 3, 3)
y <- c(4, 2, 1, 3)
The expected result would be:
[1] 4 4 4 2 2 1 3 3 3
I have a vector x, that I would like to sort based on the order of values in vector y. The two vectors are not of the same length.
x <- c(2, 2, 3, 4, 1, 4, 4, 3, 3)
y <- c(4, 2, 1, 3)
The expected result would be:
[1] 4 4 4 2 2 1 3 3 3
[Edit: Clearly Ian has the right approach, but I will leave this in for posterity.]
You can do this without loops by indexing on your y vector. Add an incrementing numeric value to y and merge them:
Here is a one liner...
[edit:] This breaks down as follows:
You could convert
x
into an ordered 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.what about this one
How about?:
(Ian's is probably still better)
In case you need to get order on "y" no matter if it's numbers or characters:
By steps: