删除所有值/行之前和之后的连续两个零

问题描述:

让我们说我有一个10x3矩阵m,我要检查所有的零和在第一列的两个连续零。我想删除在一排中的第一列包含零和与所有行也在第一列中的两个连续零从所述基质中的某一点开始后所有其他行或者去除或前值两个零。删除所有值/行之前和之后的连续两个零

 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

+0

请提供代码的数据(以机器可读格式) – HubertL

+0

@HubertL这样做。 – rapuu

+0

请使用'dput'导出您的数据 – HubertL

我给你写代码来解决以下规则:

规则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 

哪里C既是A + 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 
+0

曾为几乎完美,这只是它删除一行太多(第一行的连续2个零之后),它必须被包含在输出 – rapuu

+0

” ......之前或在连续两个零之后,去除值。 “我有点困惑。你不想两个?我写这个的方式是删除任何一行为零。此外,删除连续的零行之前和之后的任何行。这不是你想要的吗? –

+0

当你说“连续”你真的意味着在两个连续的行? XD –