从 R 中的列表中检索每个矩阵的信息

Retrieving information of each matrix from a list in R

一个可重现的例子:

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 由二进制矩阵组成,每个矩阵的行仅包含一个 1,其余填充零。

对于每个矩阵,我试图 return 一个表示列号的向量,每行 1。

预期输出:

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

最简单的形式,

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

您可以t变换它以获得您想要的尺寸。

另一个版本使用 Vectorize 而不是 max.col

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