intersect for multiple vectors in R

June 5, 2012

(This article was first published on One Tip Per Day, and kindly contributed to R-bloggers)

Say you have

a <- c(1,3,5,7,9)
<- c(3,6,8,9,10)
<- c(2,3,4,5,7,9)
A straightforward way to do the job is:
More cleverly, and more conveniently if you have a lot of arguments:
Reduce(intersect, list(a,b,c))

The Reduce function is part of funprog {base}, which includes

Reduce(f, x, init, right = FALSE, accumulate = FALSE)
Filter(f, x)
Find(f, x, right = FALSE, nomatch = NULL)
Map(f, ...)
Position(f, x, right = FALSE, nomatch = NA_integer_)

I will learn it and put notes here later.

To leave a comment for the author, please follow the link and comment on their blog: One Tip Per Day. offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Search R-bloggers


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)