选择矩阵中包含特​​定数字的列

时间:2018-01-19 16:10:43

标签: r matrix filtering

我有一个矩阵A

1   0   2
1   3   1

我想选择包含数字1的所有列。我想要的输出:

1   2
1   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