Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get all subsets up to N in R

Tags:

r

I want to generate a list that contains all 2^n subsets of the numbers 1:N in R. How is the possible?

expand.grid( rep( list( 0:4), 2))

returns a data frame containing all the subsets of 0:4 size 2 - but i want a list, that contains all subsets of all sizes.

like image 779
dan12345 Avatar asked Jan 23 '12 13:01

dan12345


People also ask

How do you find all subsets?

If a set contains 'n' elements, then the number of proper subsets of the set is 2n - 1. In general, number of proper subsets of a given set = 2m - 1, where m is the number of elements.

How many subsets of N are there?

If a set has “n” elements, then the number of subset of the given set is 2n and the number of proper subsets of the given subset is given by 2n-1.


2 Answers

How about,

lapply(0:4, function(x) combn(4,x))
[[1]]
     [,1]

[[2]]
     [,1] [,2] [,3] [,4]
[1,]    1    2    3    4

[[3]]
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    1    1    2    2    3
[2,]    2    3    4    3    4    4

[[4]]
     [,1] [,2] [,3] [,4]
[1,]    1    1    1    2
[2,]    2    2    3    3
[3,]    3    4    4    4

[[5]]
     [,1]
[1,]    1
[2,]    2
[3,]    3
[4,]    4
like image 93
James Avatar answered Sep 21 '22 02:09

James


There is a set_power function in package sets that should return the power set which is the proper term from what your words are describing. You may want to revise you terminology, though, since your code is doing something different. expand.grid does not return mathematical sets but rather ordered combinations. In set theory {1,1} reduces to {1}. Expand grid does not do real set creation in that sense. If you wanted the list of all the data.frames up to length 4 that expand.grid could make, you can get that easily enough with:

lapply(0:4, function(n) expand.grid( rep( list( 0:4), n)) )
like image 37
IRTFM Avatar answered Sep 20 '22 02:09

IRTFM