Monthly Archives: August 2018

Recursive R function to find intersection of two or more given sets

The intersect(x, y) function from R “base” package works for no more then two vectors x and y.  The following function accepts as many vectors as you like and returns the intersection vector of them all:

## recursive intersect function
intersect.rec <- function(x, ...) {
    a <- list(...)
    if(length(a) == 0) stop("Two or more arguments are needed.")
    if(is.list(a[[1]])) a <- a[[1]]
    if(length(a) == 1) return(intersect(x, a[[1]]))
    else intersect.rec(intersect(x, a[[1]]), a[-1])

Sample usage:

x <- letters[1:5]
y <- letters[2:5]
z <- letters[3:5]
intersect.rec(x, y, z)
## returns
## [1] "c" "d" "e"

This is especially a basic example of an R function using dots argument and recursively iterating over them.