Sort Vector Based on Values of Another in R
In this article, we are going to sort a vector based on values in another vector using R programming language.
We can sort the vector values based on values in the second vector by using match() and order() function. match() function is used to matches the values from the first vector to second vector. sort() function is used to sort a vector
Syntax:
vector1[order(match(vector1,vector2))]
where,
- vector1 is the first vector
- vector2 is the second vector
Example 1: R program to sort a numeric vector based on values in the second vector
R
# create a vector 1 with 10 elements vector1= c (1,2,3,4,5,6,7,8,9,10) # create a vector2 vector2= c (10,4,1,5,3,7,2,6,9,8) # sort vector 1 based on values in vector2 print (vector1[ order ( match (vector1,vector2))]) |
Output:
[1] 10 4 1 5 3 7 2 6 9 8
Example 2: Sorting with duplicate elements
R
# create a vector 1 with 20 elements vector1= c (1,2,3,4,5,6,7,8,9,10,1:10) # create a vector2 vector2= c (10,4,1,5,3,7,2,6,9,8) # sort vector 1 based on values in vector2 print (vector1[ order ( match (vector1,vector2))]) |
Output:
[1] 10 10 4 4 1 1 5 5 3 3 7 7 2 2 6 6 9 9 8 8
Please Login to comment...