通过每行奇数的计数来过滤矩阵

时间:2017-07-04 08:12:24

标签: r

有一个矩阵A,如:

       [,1] [,2] [,3] [,4] [,5] [,6]
  [1,]   11   14   17   21   23   25
  [2,]   12   15   18   24   26   28
  [3,]   13   15   19   21   25   29

我想过滤每行数为奇数的所有行< 2

因此矩阵(结果)应仅包含矩阵A的第2行。

1 个答案:

答案 0 :(得分:2)

我们可以使用apply指定MARGIN =1遍历行,创建逻辑vector以对矩阵'm1'进行子集

m1[apply(m1, 1, FUN = function(x) sum(x %% 2) < 2),, drop = FALSE]
#     [,1] [,2] [,3] [,4] [,5] [,6]
#[1,]   12   15   18   24   26   28

rowSums

m1[rowSums((m1 %%2)) <2, , drop = FALSE]
#     [,1] [,2] [,3] [,4] [,5] [,6]
#[1,]   12   15   18   24   26   28

编辑:基于@ lmo的评论

数据

m1 <- structure(c(11, 12, 13, 14, 15, 15, 17, 18, 19, 21, 24, 21, 23, 
     26, 25, 25, 28, 29), .Dim = c(3L, 6L))