Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (5.3k points)
edited by

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

1 Answer

0 votes
by
edited by

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.

A one-line form:

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

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

Browse Categories

...