On Nov 21, 2011, at 11:42 AM, R. Michael Weylandt wrote:
> I'd appreciate it if you'd keep on list for the archives. That
said, I
> think this function does what you were hoping for.
>
> Michael
>
> powerset <- function(n, items = NULL){
> if(!is.null(items)) {
> if(n != length(items)) warning("Resetting n in preference to
> length(items)")
> n = length(items)
> }
>
> smat <- do.call(expand.grid, rep(list(c(0,1)), n))
>
> if(!is.null(items))
> smat <- smat * matrix(items, ncol = n, nrow = 2^n, byrow = T)
> smat
> }
>
Michael's function is very nice (although the n= parameter seems
superfluous since any value other than the length of 'items' will get
discarded). However, your use case was not specified so I cannot know
if you wanted set notation or matrix class objects. Here's another
option in case you wanted set notation:
> require(sets)
Loading required package: sets
> as.set(c(2,3,4,5))
{2, 3, 4, 5}
> X <- as.set(c(2,3,4,5))
> set_power(X)
{{}, {2}, {3}, {4}, {5}, {2, 3}, {2, 4}, {2, 5}, {3, 4}, {3, 5}, {4, 5},
{2, 3, 4}, {2, 3, 5}, {2, 4, 5}, {3, 4, 5}, {2, 3, 4, 5}}
The set package offers an extensive list of set oriented functions.
--
David.
> On Sat, Nov 19, 2011 at 8:49 PM, Gyanendra Pokharel
> <gyanendra.pokharel at gmail.com> wrote:
>> Hi Michael,
>> I have trouble to find the subsets of a given set. For example x <-
>> c(2, 3,
>> 4, 5), there will be 16 subsets of this set
>> in the matrix form
>> 0 0 0 0
>> 1 0 0 0
>> 0 1 0 0
>> 0 0 1 0
>> 0 0 0 1
>> 1 1 0 0
>> 0 1 1 0
>> 0 0 1 1
>> 0 1 0 1
>> 1 0 1 0
>> 1 0 1 1
>> 1 1 1 0
>> 0 1 1 1
>> 1 0 1 1
>> 1 1 0 1
>> 1 1 1 1
>> times transpose(x) , but how could I produce in R?
>> Thanks in advance
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
David Winsemius, MD
West Hartford, CT