我有一个矩阵A
:
1 0 2
1 3 1
我想选择包含数字1的所有列。我想要的输出:
1 2
1 1
答案 0 :(得分:2)
数据强>
A = matrix(c(1, 1, 0, 3, 2, 1), nrow = 2)
A
# [,1] [,2] [,3]
#[1,] 1 0 2
#[2,] 1 3 1
<强> 1 强>
A[,colSums(A == 1, na.rm = TRUE) > 0, drop = FALSE]
# [,1] [,2]
#[1,] 1 2
#[2,] 1 1
<强> 2 强>
A[,apply(A, 2, function(x) any(x == 1)), drop = FALSE]
# [,1] [,2]
#[1,] 1 2
#[2,] 1 1