listing all subsets of a vector for a given size

amit picture amit · May 10, 2014 · Viewed 7.9k times · Source

The function choose(n,k) tells us how many subsets of size k exists for a set of n distinct elements. Suppose I need to actually list those subsets, how I create it? in other words I'm looking for a function that accepts a vector x (of length n) and a number k and returns a list of vectors, each of size k, with subsets of x. the length of the list should be, of course, choose(length(x),k). for example

enum.choose = function(x,k) {
    # implementation should go here
{

enum.choose(1:3,2)

# should be:
# [[1]]
#    1  2
# [[2]]
#    1  3
# [[3]]
#    2  3

Answer

Rich Scriven picture Rich Scriven · May 11, 2014

EDIT


I realized that combn(1:3, 2, simplify = FALSE) gives you the list result you're looking for. If @Ramnath wishes to post an answer, this one will be deleted.

> combn(1:3, 2, simplify = FALSE)
## [[1]]
## [1] 1 2

## [[2]]
## [1] 1 3

## [[3]]
## [1] 2 3

So using an *apply function on it will make the following function irrelevant.


Original


Making use of the comment from @Ramnath, your function might be something like this:

enum.choose <- function(x, k) {
  if(k > length(x)) stop('k > length(x)')
  if(choose(length(x), k)==1){
    list(as.vector(combn(x, k)))
  } else {
    cbn <- combn(x, k)
    lapply(seq(ncol(cbn)), function(i) cbn[,i])
  }
}

Test runs:

> enum.choose(1:3, 2)
# [[1]]
# [1] 1 2
# 
# [[2]]
# [1] 1 3
# 
# [[3]]
# [1] 2 3
> enum.choose(c(1, 2, 5, 4), 3)
# [[1]]
# [1] 1 2 5
# 
# [[2]]
# [1] 1 2 4
# 
# [[3]]
# [1] 1 5 4
# 
# [[4]]
# [1] 2 5 4
> enum.choose(1:4, 4)
# [[1]]
# [1] 1 2 3 4
> enum.choose(1:5, 6)
# Error in enum.choose(1:5, 6) : k > length(x)