Reputation: 591
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
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
Reputation: 160447
In its simplest form,
sapply(ex.list, max.col)
# [,1] [,2]
# [1,] 1 2
# [2,] 3 3
# [3,] 1 4
You can t
ranspose it to get the dimensions you seek.
Upvotes: 6