Home > front end >  R: given a list of matrices, determine which ones have a specified value in a specific element
R: given a list of matrices, determine which ones have a specified value in a specific element

Time:05-21

I have a list L of length k whose elements are matrices of equal dimension n x m. Suppose I want to know which of the matrices in the list satisfy the condition M[i,j]==1.

Obviously,

grep(1, L)

will not work as it will return all instances of 1 in the matrices, rather than just those where 1 occurs in position i,j. Is there any way to do this other than using a for loop and checking each matrix individually?

As a simple example, if I have a list of three matrices:

m1 = rbind(c(0,0,0),c(0,0,0),c(1,1,1)
m2 = rbind(c(1,1,1),c(1,0,0),c(0,0,0)
m3 = rbind(c(0,0,0),c(0,1,0),c(1,1,1)
mlist = list(m1,m2,m3)

I would like to find for which matrix/matrices in mlist M[2,2]=1, the correct output would be 3, since the third matrix in the list satisfies this condition.

CodePudding user response:

Let's make a reproducible example. We create a list of three 3 x 3 matrices called L which are filled with zeros. We define i = 2 and j = 3, and put a 1 at the i, j index of our third matrix.

m <- matrix(0, 3, 3)
L <- list(m, m, m)
i <- 2
j <- 3
L[[3]][i, j] <- 1

L
#> [[1]]
#>      [,1] [,2] [,3]
#> [1,]    0    0    0
#> [2,]    0    0    0
#> [3,]    0    0    0
#> 
#> [[2]]
#>      [,1] [,2] [,3]
#> [1,]    0    0    0
#> [2,]    0    0    0
#> [3,]    0    0    0
#> 
#> [[3]]
#>      [,1] [,2] [,3]
#> [1,]    0    0    0
#> [2,]    0    0    1
#> [3,]    0    0    0

Now to answer the question, we want an expression that finds which of the three matrices has a 1 at position i, j. To get this, we can do:

which(sapply(L, function(x) x[i, j] == 1))
#> [1] 3

Created on 2022-05-20 by the reprex package (v2.0.1)

  •  Tags:  
  • r
  • Related