Back

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)

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

To sort one vector based on values of another vector, you can use the match() and order() function from the base package as follows:

x <- c(2, 2, 3, 4, 1, 4, 4, 3, 3)y <- c(4, 2, 1, 3) match(x,y)[1] 2 2 4 1 3 1 1 4 4 #returns the relative position of the elements from x to y.order(match(x,y))[1] 4 6 7 1 2 5 3 8 9 #orders the indices in arranging order.x[order(match(x,y))][1] 4 4 4 2 2 1 3 3 3 #sorts elements of x based on y.

match(x,y)

[1] 2 2 4 1 3 1 1 4 4 #returns the relative position of the elements from x to y.

order(match(x,y))

[1] 4 6 7 1 2 5 3 8 9 #orders the indices in arranging order.

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

[1] 4 4 4 2 2 1 3 3 3 #sorts elements of x based on y.

A one-line form:

x[order(match(x,y))][1] 4 4 4 2 2 1 3 3 3

30.9k questions

32.9k answers

500 comments

665 users