去掉连续两个零前后的所有values/rows

Remove all values/rows before and after two consecutive zeros

假设我有一个 10x3 矩阵 m,我想在其中检查第一列中的所有零和两个连续的零。我想删除第一列中包含零的所有行以及第一列中从矩阵中的某个点开始的两个连续零之后的所有其他行,并删除值 before 连续两个零之后。

      col1 col2 col3
[1,]    2    2    2
[2,]    2    2    2
[3,]    2    2    2
[4,]    2    2    2
[5,]    2    0    2
[6,]    2    2    2
[7,]    2    0    2
[8,]    2    0    2
[9,]    2    2    2
[10,]   2    2    2

dput= structure(c(2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 0, 
0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2), .Dim = c(10L, 3L), .Dimnames = list(
NULL, c("col1", "col2", "col3")))


expected result=     col1 col2 col3
                [1,]    2    2    2
                [2,]    2    2    2

删除第 1、2、3、4、5、6、7 和 8 行。

我已经为您编写了解决以下规则的代码:

规则 A: 删除任何列中包含零的行

规则 B: 删除任何列中连续零之前的所有行

1 2 3 4 5 6 7 8 9 10 # Row Number
2 2 2 2 0 2 0 0 2 2  # Column 2
* * * * * * * * 2 2  # * = Remove
B B B B C B A A - -  # Rule Why Removed

其中 CA+B 发生的地方。如果在第 10 行之后有以下行具有单个(非连续)零,它们将被删除。

这里我们删除了1:8。 这是我的方法:

dat <- structure(c(2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 0, 
                  0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2), .Dim = c(10L, 3L), .Dimnames = list(
                    NULL, c("col1", "col2", "col3")))
dat

ToRemove <- apply(dat, 2, function(colmn) {
  row.zeros <- which(colmn == 0) # rows with zeros
  if(length(row.zeros) > 0) { # if we found any
     # which of them is the last double
    last.doubles <- max(which(diff(row.zeros) == 1))
    leftof.last.doubles <- "if"(length(last.doubles) > 0, # if double exists
                                1:(row.zeros[last.doubles]-1), # all rows before
                                NULL) # else nothing
    # remove rows with single zeros and all rows before double consecutive 
    unique(c(row.zeros, leftof.last.doubles)) }
})

ToRemove
#$col1
#NULL
#
#$col2
#[1] 5 7 8 1 2 3 4 6
#
#$col3
#NULL

dat[-unlist(ToRemove),]
#     col1 col2 col3
#[1,]    2    2    2
#[2,]    2    2    2