Search code examples
rlistmatrixlapplysapply

Retrieving information of each matrix from a list in R


A reproducible example:

mat1 <- matrix(c(1,0,0,0,0,0,1,0,1,0,0,0), nrow = 3, ncol = 4, byrow = T)
mat2 <- matrix(c(0,1,0,0,0,0,1,0,0,0,0,1), nrow = 3, ncol = 4, byrow = T)
ex.list <- list(mat1,mat2)

> ex.list
[[1]]
      [,1] [,2] [,3] [,4]
[1,]    1    0    0    0
[2,]    0    0    1    0
[3,]    1    0    0    0

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

ex.list consists of binary matrices and row of each of these matrices contain only a single 1 and rest are filled with zeros.

For each matrix I am trying to return a vector that indicates the column number with 1 for each rows.

Expected output:

      [,1] [,2] [,3]
[1,]    1    3    1
[2,]    2    3    4

Solution

  • In its simplest form,

    sapply(ex.list, max.col)
    #      [,1] [,2]
    # [1,]    1    2
    # [2,]    3    3
    # [3,]    1    4
    

    You can transpose it to get the dimensions you seek.