删除特定列

Delete specific columns

我有

F <- structure(c(0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0), .Dim = c(3L, 
5L))

如何从 F 中删除连续少于 2 个零的列? 谢谢!

我们可以使用 rle 来确定连续值,即 0,并通过遍历列 (apply, MARGIN = 2)lengths 创建逻辑条件

F[,!apply(F, 2, function(x) with(rle(!x), 
      any(lengths >= 2 & values))), drop = FALSE]

-输出

      [,1] [,2]
[1,]    0    0
[2,]    1    1
[3,]    1    1

如果是相反的,就去掉!

F[,apply(F, 2, function(x) with(rle(!x), 
      any(lengths >= 2 & values))), drop = FALSE]
      [,1] [,2] [,3]
[1,]    1    1    1
[2,]    0    0    0
[3,]    0    0    0

在列上应用 rle 的方法略有不同:

F[, apply(F, 2, \(x) with(rle(x), any(lengths[values == 0] >= 2)))]

     [,1] [,2] [,3]
[1,]    1    1    1
[2,]    0    0    0
[3,]    0    0    0

使用纯base,没有额外的功能,如one-liner:

U = F[, apply((F[-1,]==0) & (F[-nrow(F),]==0), 2, any)]

细分:

U = F[                                   # Select...
   ,                                     # ...all the rows in the matrix...
   apply(                                # ...that have...
      (F[-nrow(F),]==0) & (F[-1,]==0),   # ...one value = 0 and the next value = 0
      2,                                 # ...in columns (i.e. 2nd dimension)....
      any                                # ...anywhere in the column.
    )
]