从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,其余的用零填充。
对于每个矩阵,我试图返回一个向量,该向量指示每行 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对它进行调整以获得所需的尺寸。