获取R中由向量指示的所有列的元素等于x的行的索引

han*_*frc 2 r matrix

让我们有一个矩阵M,例如

> M
     [,1] [,2] [,3] [,4]
[1,]   15    0    0    9
[2,]    0    1    8   24
[3,]    4    0    0    0
[4,]    3    2    0    0
[5,]    0    0   56    0
Run Code Online (Sandbox Code Playgroud)

列索引的向量ind,例如

> ind=c(2,4)
> ind
[1] 2 4
Run Code Online (Sandbox Code Playgroud)

和一个值x,例如x=0.

如何获取矩阵行的索引M,其所指示的所有列的元素ind等于x

以下代码返回正确的行索引:

> which(M[,2]==0 & M[,4]==0)
[1] 3 5
Run Code Online (Sandbox Code Playgroud)

但我需要一个使用矢量的解决方案ind,可能很长.我试过了:

> which(M[,ind]==0)
[1]  1  3  5  8  9 10
Run Code Online (Sandbox Code Playgroud)

但相反,我得到的条目在任何一个列中都有零ind,而不是同时在所有列中.

Ric*_*ven 8

怎么样

rowSums(M[, ind] == 0) == length(ind)
# [1] FALSE FALSE  TRUE FALSE  TRUE
Run Code Online (Sandbox Code Playgroud)

让我们一步一步地打破代码:

  • M[, ind] == 0- 得到一个显示M[, ind]零点的逻辑矩阵
  • rowSums(.) - 确定每行中有多少TRUE值
  • . == length(ind) - 将其与使用的列数进行比较

如果你需要数字索引,请将其包装which().

which(rowSums(M[, ind] == 0) == length(ind))
# [1] 3 5
Run Code Online (Sandbox Code Playgroud)

数据:

M <- structure(c(15L, 0L, 4L, 3L, 0L, 0L, 1L, 0L, 2L, 0L, 0L, 8L, 
0L, 0L, 56L, 9L, 24L, 0L, 0L, 0L), .Dim = c(5L, 4L), .Dimnames = list(
    NULL, c("V1", "V2", "V3", "V4")))
ind <- c(2, 4)
Run Code Online (Sandbox Code Playgroud)