Skip to content

Instantly share code, notes, and snippets.

@cbare
Created October 24, 2012 19:35
Show Gist options
  • Select an option

  • Save cbare/3948302 to your computer and use it in GitHub Desktop.

Select an option

Save cbare/3948302 to your computer and use it in GitHub Desktop.
Compute the intersection of all combinations of a list of vectors
## Compute the intersection of all combinations of the
## elements in the list of vectors l. Might be useful
## for generating Venn/Euler diagrams.
## There might be better ways to do this!
overlap <- function(l) {
results <- list()
# combinations of m elements of list l
for (m in seq(along=l)) {
# generate and iterate through combinations of length m
for (indices in combn(seq(length(l)), m, simplify=FALSE)) {
# make name by concatenating the names of the elements
# of l that we're intersecting
name <- do.call(paste, c(as.list(names(l)[indices]), sep="_"))
# adding the init=l[indices[1]] parameter helps with the case
# where we're only dealing with one set, i==1 and length(indices)==1,
# and we want only unique items in that set.
# Reduce(intersect, list(c(1,2,3,3))) => c(1,2,3,3)
# Reduce(intersect, list(c(1,2,3,3)), init=l[[indices[1]]]) => c(1,2,3)
results[[name]] <- Reduce(intersect, l[indices], init=l[[indices[1]]])
}
}
results
}
# test it out!
overlap( list(foo=c('a','b','c','d','e','e'), bar=c('a','c','e','f','g'), bat=c('a','b','c','d','g')))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment