# 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