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.

2 thoughts on “Recursive R function to find intersection of two or more given sets

  1. Hi, I like this function, I have written similar versions to it in the past, but since then I have found this base R trick, which when adapted to your example gives:

    Reduce(intersect, list(x, y, z))
    ## returns
    ## [1] “c” “d” “e”

Leave a Reply

Your email address will not be published. Required fields are marked *