如何在特定条件下查找 R 中的特定行或列

how to find particular rows or columns in R with specific conditions

例如,如果我们有一个具有以下格式的矩阵或数组

M = matrix(c(1,1,0,0,0,1,0,1,0,0,0,0,1,1,0,1), # the data elements 
    nrow=4,              # number of rows 
    ncol=4,              # number of columns 
    byrow = TRUE)        # fill matrix by rows 

如何找到哪些行和列的索引里面只有0? 如果我们有一个更复杂的矩阵,我们需要找出其中所有数字在特定区间内的行或列怎么办?

M = matrix(c(1,1,12,34,0,19,15,1,0,17,12,0,21,1,11,1), # the data elements 
    nrow=4,              # number of rows 
    ncol=4,              # number of columns 
    byrow = TRUE)        # fill matrix by rows 

我应该如何找到所有数字都在 (10 - 20) 之间的列?

非常感谢任何可以提供帮助的人。

而且,我也不能使用 for 或 while 循环来处理它。

你可以这样做:

 which(apply(M, 1, sum) == 0 )
[1] 3
 which(apply(M, 2, sum) == 0 )
[1] 3

1 中搜索行,在 2 中搜索列。结果告诉您哪一行和哪一列全为零。使用 M 您可以看到第 3 行和第 3 列只有零。

或者按照 Akrun 的建议,您可以使用 rowSumscolSums 应该会更快。

 which(rowSums(M) == 0)
[1] 3
 which(colSums(M) == 0)
[1] 3