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.
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.
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.
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
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)) )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With