2016-06-12 92 views
2

我有一个如下所示的数据框,它是分类器的输出。在R数据框中查找列值跟在序列后面的行

col1, class 
123, 2 
122, 5 
124, 7 
125, 9 
126, 15 
127, 2 
128, 19 
129, 5 
130, 7 
179, 9 
180, 3 

我想找到有类的一定的模式,就像它的类在SEQ 5,7,9所有行的行。

我想出了解决方案通过移位一行和比较列如下

col1, class, class1, class2 
123, 2,5,7 
122, 5,7,9 
124, 7,9,15 
125, 9,15,2 
126, 15,2,19 
127, 2,19,5 
128, 19,5,7 
129, 5,7,9 
130, 7,9,3 
179, 9,3,NA, 
180, 3,NA,NA 

这解决了只有我的图案场的数量是相同的,但我会改变的是粘贴班列。有些模式甚至可能有5至7个字段。

回答

2

我们可以使用shiftdata.table,然后paste的元素结合在一起,并检查,我们有579

n <- 3 
library(data.table) 
setDT(df1)[, which(do.call(paste0, shift(class, seq(n)-1, type = "lead"))=="579")] 
#[1] 2 8 

或代替paste我们可以使用MapReduce

setDT(df1)[, which(Reduce(`&`, Map(`==`, shift(class, seq(n)-1, 
      type = "lead"), c(5, 7, 9))))] 
#[1] 2 8 
2

稍微更长时间基础R替代,原则上类似于@ akrun的回答:

which(do.call(paste0, cbind(df1, with(df1, class[seq_along(class)+1]), 
          with(df1, class[seq_along(class)+2]))[-1]) == "579") 
#[1] 2 8 

数据:

df1 <- structure(list(col1 = c(123L, 122L, 124L, 125L, 126L, 127L, 128L, 
           129L, 130L, 179L, 180L), class = c(2L, 5L, 
           7L, 9L, 15L, 2L, 19L, 5L, 7L, 9L, 3L)), 
           .Names = c("col1", "class"), class = "data.frame", 
           row.names = c(NA, -11L)) 
+1

我觉得还有用'matrix'选项 – akrun

相关问题