Skip to content

Sub sets

2 messages · R. Michael Weylandt, David Winsemius

#
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
}

On Sat, Nov 19, 2011 at 8:49 PM, Gyanendra Pokharel
<gyanendra.pokharel at gmail.com> wrote:
#
On Nov 21, 2011, at 11:42 AM, R. Michael Weylandt wrote:

            
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.