Algorithm to calculate power set (all possible subsets) of a set in R

后端 未结 4 1485
故里飘歌
故里飘歌 2020-12-11 05:52

I couldn\'t find an answer to this anywhere, so here\'s my solution.

The question is: how can you calculate a power set in R?

It is possible to do this with

4条回答
  •  暖寄归人
    2020-12-11 06:00

    A subset can be seen as a boolean vector, indicating whether an element is in the subset of not. Those boolean vectors can be seen as numbers written in binary. Enumerating all the subsets of 1:n is therefore equivalent to enumerating the numbers from 0 to 2^n-1.

    f <- function(set) { 
      n <- length(set)
      masks <- 2^(1:n-1)
      lapply( 1:2^n-1, function(u) set[ bitwAnd(u, masks) != 0 ] )
    }
    f(LETTERS[1:4])
    

提交回复
热议问题