Intersection in R

Intersection of two vectors

To get the common elements between two vectors we can use the built-in function intersect:

> v1 <- c(1, 2, 3)
> v2 <- c(2, 3, 4)
> intersect(v1, v2)
[1] 2 3

Intersection of a list of vectors

Here we want the common elements between all the vectors in the list.

intersect.list <- function(list.vec) {
    return(Reduce(intersect, list.vec))
}

> ll <- list()
> ll$c1 <- c(1, 2, 3)
> ll$c2 <- c(2, 3, 4)
> intersect.list(ll)
[1] 2 3
> ll$c3 <- c(3, 4, 5)
> intersect.list(ll)
[1] 3
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: