在R中查找data.table行中的模式

时间:2015-06-30 21:42:39

标签: r data.table

我正在尝试跨data.table的行查找模式,同时仍然保持跨行的数据链接。这是一个简化的例子:

var c = function(){           
    // functions also get hoisted to the top
    function _callAfter(){
        alert(y);
    }
    var x = 'before',
        callBefore = function(){
            alert(x);
        },
        callAfter = function(){
            _callAfter();
        },
        // y declaration is hoisted to the top of the function
        y;

    return {
        callBefore : callBefore,
        callAfter : callAfter
    };

    // the assignment never gets called because it's after the return
    y = 'after';
};

我想搜索" ATB"的所有实例。在连续的行中输出值列中的整数。理想情况下,我也希望将实例数量合并。输出表如下所示:

Row ID Value
1   C  1000
2   A  500
3   T  -200
4   B  5000
5   T  -900
6   A  300

由于data.table包似乎是针对以列或行为基础提供操作,我认为这应该是可能的。但是,我没有任何想法从哪里开始。任何指向正确方向的人都会非常感激。

谢谢!

1 个答案:

答案 0 :(得分:0)

library("plyr")
library("stringr")
df <- read.table(header = TRUE, text = "Row ID Value
                 1   C  1000
                 2   A  500
                 3   T  -200
                 4   B  5000
                 5   T  -900
                 6   A  300
                 7   C  200
                 8   A  700
                 9   T  -500")
sought <- c("ATB", "CAT", "NOT")
ids <- paste(df$ID, collapse = "")
ldply(sought, function(id) {
    found <- str_locate_all(ids, id)
      if (nrow(found[[1]])) {
            vals <- outer(found[[1]][,"start"], 0:2, function(x, y) df$Value[x + y])
      } else {
            vals <- as.list(rep(NA, 3))
      }
      data.frame(ID = id, Count = str_count(ids, id),
                 setNames(as.data.frame(vals), paste0("Value", 1:3)))
})

以下是使用stringrplyr的解决方案。将ID折叠为单个字符串,找到每个目标的所有实例,然后使用相关列构建数据框。