通过r中的条件从矩阵中删除特定的行或列

时间:2018-01-17 21:30:36

标签: r

我创建了一个矩阵mat。第一行包含所有0' s。

mat <- matrix(c(0,0,0,1,0,3,4,5), nrow=4)
mat


     [,1] [,2]
[1,]    0    0
[2,]    0    3
[3,]    0    4
[4,]    1    5

我想要做的是删除第一行,因此它变为2x3矩阵。我想使用布尔条件,以便它可以应用于任何情况。 如果这是一个数据帧,这可以很容易地完成。但我不知道如何以矩阵形式做到这一点。非常感谢提前。

1 个答案:

答案 0 :(得分:1)

您可以使用which

#will give you the indices of rows
rows <- unique(which(mat == 0, arr.ind = TRUE)[, 1])
#will give you the indices of columns
cols <- unique(which(mat == 0, arr.ind = TRUE)[, 2])

#then you can do whatever you want
#remove rows
mat[-rows, ]
#remove columns
mat[, -cols]
#remove all
mat[-rows, -cols]
相关问题