Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get indices of rows whose elements equal x at all columns indicated by a vector, in R

Tags:

r

matrix

Let us have a matrix M, e.g.

> 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

a vector of its column indices ind, e.g.

> ind=c(2,4)
> ind
[1] 2 4

and a value x, e.g. x=0.

How to get the indices of rows of matrix M, whose elements at all columns indicated by ind are equal to x?

The following code returns proper row indices:

> which(M[,2]==0 & M[,4]==0)
[1] 3 5

but I need a solution that will use a vector ind, possibly very long. I tried:

> which(M[,ind]==0)
[1]  1  3  5  8  9 10

but instead I got the entries which have zeros in either of the columns indicated by ind, not in all of them at the same time.

like image 790
hanna Avatar asked Nov 30 '25 03:11

hanna


1 Answers

How about

rowSums(M[, ind] == 0) == length(ind)
# [1] FALSE FALSE  TRUE FALSE  TRUE

Let's break the code down step-by-step:

  • M[, ind] == 0 - get a logical matrix showing where M[, ind] is zero
  • rowSums(.) - determine how many TRUE values are in each row
  • . == length(ind) - compare it to the number of columns used

And if you need the numeric indices, wrap it in which().

which(rowSums(M[, ind] == 0) == length(ind))
# [1] 3 5

Data:

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)
like image 114
Rich Scriven Avatar answered Dec 01 '25 16:12

Rich Scriven