Rel_Ai
Rel_Ai

Reputation: 591

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

Upvotes: 3

Views: 49

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 101373

Another version is using Vectorize over max.col

> Vectorize(max.col)(ex.list)
     [,1] [,2]
[1,]    1    2
[2,]    3    3
[3,]    1    4

Upvotes: 2

r2evans
r2evans

Reputation: 160447

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.

Upvotes: 6

Related Questions