【问题标题】:How to apply a combination function on data.table rows to extract and record the different possibilities in another data.table?如何对 data.table 行应用组合函数来提取和记录另一个 data.table 中的不同可能性?
【发布时间】:2019-07-08 16:00:05
【问题描述】:

我遇到了一个问题,我在以前的帖子中找不到合适的方法来解决它。 我有下面的数据表,其中有 one 列:

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

我想找到一种方法来获取另一个数据表中每一行中的元素组合,如下所示。 基本上,我想先获取每一行,然后两两,然后像这样继续,直到最后我得到所有选项。

       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

感谢您在这方面的帮助。

【问题讨论】:

    标签: r list data.table combinations combn


    【解决方案1】:

    这是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
    }))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-15
      • 2019-12-16
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多