有一个矩阵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行。
答案 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))