Sort Vector Based on Values of Another in R (Example)
In this article, I’ll show how to sort a vector according to the values of another vector in the R programming language.
The tutorial contains the following information:
- Creation of Example Data
- Example: How to Sort First Vector According to Second
- Video, Further Resources & Summary
Let’s dig in:
Creation of Example Data
First, we have to create an unsorted example vector in R:
x1 <- c("a", "d", "a", "b", "b", "c", "a", "d") # Create example vector
As you can see, our example vector consists of several letter elements ranging from “a” to “d”. The elements of our example vector are unordered.
Second, we have to create another vector containing the desired ordering:
x2 <- c("b", "d", "a", "c") # Create sorting order
Our sorting vector specifies that we want to order our first vector in the order “b”, “d”, “a”, “c”.
Example: How to Sort First Vector According to Second
If we want to rearrange the order of our first vector based on the second vector, we can use a combination of the order and match functions. Have a look at the following R code:
x1[order(match(x1, x2))] # Order vector according to x2 # "b" "b" "d" "d" "a" "a" "a" "c"
As you can see based on the output of the RStudio console, the output of the previous R syntax is a new vector consisting of the elements of the first vector sorted according to the elements of the second vector.
Video, Further Resources & Summary
Do you need more info on the content of this page? Then you may have a look at the following video of my YouTube channel. In the video, I illustrate the R syntax of this tutorial:
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
In addition to the video, you may want to read the related R tutorials of statisticsglobe.com. A selection of related articles can be found here.
You learned in this tutorial how to reorder one vector (or array) based on the elements of another vector in the R programming language. Please let me know in the comments, if you have further questions.
Statistics Globe Newsletter