Mittwoch, 16. Mai 2012

Find all subsets

How can we get all subsets of a vector's elements?

all.subsets <- function(x, min.n=1, max.n=length(x)){
  # return a list with all subsets of x
  # Caution: This can be heavy for moderate lengths of x11
  lst <- lapply( min.n:max.n, function(i) {
    m <- combn(x,i) # this is a matrix, split into it's columns
    lapply( seq_len(ncol(m)), function(k) m[,k])
  } )
  # Alternative:
  # lst <- lapply(min.n:max.n, function(i) lapply(apply(combn(x,i),2,list),unlist))

  # and now flatten the list of lists into one list
  lst <- split(unlist(lst), rep(1:length(idx <- rapply(lst, length)), idx))
  return(lst)
}

# example:
y <- letters[1:5]
all.subsets(y)

Keine Kommentare: