Search code examples
rlistdata.tablecombinationscombn

How to apply a combination function on data.table rows to extract and record the different possibilities in another data.table?


I have faced a problem and I could not find a proper method to solve it on previous posts. I have the data table below which has one column:

             listOfRules
1:  a, fire, addAfter, b
2: b, storm, addAfter, c
3:      c, storm, remove

I'd like to find a way to get the combination of the elements in each row in another data table like the one in below. Basically, I want to first get each individual row, then, two by two, and continue like this until finally I get all of the options.

       x1                           x2                    x3
1. a, fire, addAfter, b             NA                    NA
2. b, storm, addAfter, c            NA                    NA
3. c, storm, remove                 NA                    NA
4. a, fire, addAfter, b      b, storm, addAfter, c        NA
5. a, fire, addAfter, b      c, storm, remove             NA
6. b, storm, addAfter, c     c, storm, remove             NA
7. a, fire, addAfter, b      b, storm, addAfter, c     c, storm, remove

I would appreciate your help on this one.


Solution

  • Here is a simple approach in base R

    v <- letters[1:3]
    lenV <- length(v)
    
    do.call(rbind, lapply(1:lenV, function(x) {
        mat <- t(combn(v, x))
    
        if (ncol(mat) < lenV)
            cbind(mat, replicate(lenV - ncol(mat), rep(NA, nrow(mat))))
        else
            mat
    }))