Find Common Elements from Multiple Vectors in R (Example)
In this article, I’ll show how to identify shared elements of multiple vectors in the R programming language.
Table of contents:
So now the part you have been waiting for – the examples…
Creating Example Data
Consider the following three character vectors in R:
x1 <- c("A", "B", "C", "D", "E") # Create example vectors x2 <- c("A", "C", "D") x3 <- c("A", "B", "D")
Our three vectors contain several letters, whereby the letters “A” and “D” are included in all vectors.
Example: Find Common Vector Elements
If we want to identify all elements of our vectors, which are existent in each of the vectors, we can use a combination of the Reduce(), intersect(), and list() functions. Have a look at the following R code:
Reduce(intersect, list(x1, x2, x3)) # Identify common elements # "A" "D"
The previous R code returns “A” and “D” to the RStudio console – The two letters that are contained in all of our vectors.
Within the list function, you can specify as many vector or data frame column elements as you want. The previous R syntax will return all common elements of the vectors in this list.
Video & Further Resources
If you need further explanations on the R syntax of this tutorial, you may watch the following video of my YouTube channel. I illustrate the topics of this article in the video.
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.
Additionally, you may want to read the related articles of this website. A selection of tutorials can be found below:
Summary: In this article, I showed how to get common values between multiple vectors or columns in R programming. If you have further questions, don’t hesitate to let me know in the comments section. Furthermore, don’t forget to subscribe to my email newsletter for updates on the newest tutorials.
Statistics Globe Newsletter
2 Comments. Leave new
Thanks, but how do you know which unique element came from which vector?
Hey Efrat,
Are you looking for the setdiff function?
Have a look here for more details.
Regards,
Joachim