Search code examples
rcombinationspowerset

Unordered combinations of all lengths


I am looking a function that return me all the unordered combination of a vector. eg

x <- c('red','blue','black')
uncomb(x)
[1]'red'
[2]'blue'
[3]'black'
[4]'red','blue'
[5]'blue','black'
[6]'red','black'
[7]'red','blue','black'

I guess that there is a function in some library that do this, but in can't find it. I am trying with permutations of gtool but it is not the function i am looking for.


Solution

  • You could apply a sequence the length of x over the m argument of the combn() function.

    x <- c("red", "blue", "black")
    do.call(c, lapply(seq_along(x), combn, x = x, simplify = FALSE))
    # [[1]]
    # [1] "red"
    # 
    # [[2]]
    # [1] "blue"
    # 
    # [[3]]
    # [1] "black"
    # 
    # [[4]]
    # [1] "red"  "blue"
    # 
    # [[5]]
    # [1] "red"   "black"
    # 
    # [[6]]
    # [1] "blue"  "black"
    # 
    # [[7]]
    # [1] "red"   "blue"  "black"
    

    If you prefer a matrix result, then you can apply stringi::stri_list2matrix() to the list above.

    stringi::stri_list2matrix(
        do.call(c, lapply(seq_along(x), combn, x = x, simplify = FALSE)),
        byrow = TRUE
    )
    #      [,1]    [,2]    [,3]   
    # [1,] "red"   NA      NA     
    # [2,] "blue"  NA      NA     
    # [3,] "black" NA      NA     
    # [4,] "red"   "blue"  NA     
    # [5,] "red"   "black" NA     
    # [6,] "blue"  "black" NA     
    # [7,] "red"   "blue"  "black"