Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find common elements from multiple vectors?

Tags:

r

r-faq

vector

People also ask

How do you find the common element of multiple vectors in R?

1 Answer. To find the common elements from multiple vectors, you can use the intersect function from the sets base R package. vectors (of the same mode) containing a sequence of items (conceptually) with no duplicate values. Intersect will discard any duplicated values in the arguments, and they apply as.

How do you find common elements in two columns in R?

To find the common elements between two columns of an R data frame, we can use intersect function.

How do you find the intersection of two vectors in C++?

std::set_intersection in C++ The intersection of two sets is formed only by the elements that are present in both sets. The elements copied by the function come always from the first range, in the same order. The elements in the both the ranges shall already be ordered.


There might be a cleverer way to go about this, but

intersect(intersect(a,b),c)

will do the job.

EDIT: More cleverly, and more conveniently if you have a lot of arguments:

Reduce(intersect, list(a,b,c))

A good answer already, but there are a couple of other ways to do this:

unique(c[c%in%a[a%in%b]])

or,

tst <- c(unique(a),unique(b),unique(c))
tst <- tst[duplicated(tst)]
tst[duplicated(tst)]

You can obviously omit the unique calls if you know that there are no repeated values within a, b or c.


intersect_all <- function(a,b,...){
  all_data <- c(a,b,...)
  require(plyr)
  count_data<- length(list(a,b,...))
  freq_dist <- count(all_data)
  intersect_data <- freq_dist[which(freq_dist$freq==count_data),"x"]
  intersect_data
}


intersect_all(a,b,c)

UPDATE EDIT A simpler code

intersect_all <- function(a,b,...){
  Reduce(intersect, list(a,b,...))
}

intersect_all(a,b,c)