Sort Vector Based on Values of Another in R
Last Updated :
23 Sep, 2021
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
vector1= c (1,2,3,4,5,6,7,8,9,10)
vector2= c (10,4,1,5,3,7,2,6,9,8)
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
vector1= c (1,2,3,4,5,6,7,8,9,10,1:10)
vector2= c (10,4,1,5,3,7,2,6,9,8)
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
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...