在R中创建多个相同(相同维度)矩阵的列表

时间:2014-12-09 14:33:29

标签: r list matrix paste dimensions

我正在创建相同大小的 N 数量的矩阵 M1,M2,... Mn )( C x R )并将其存储在列表 L 中。

我的代码如下:

C=2 #columns
R=3 #rows
N=6 #number of matrices
M1 <- matrix(0, ncol=C, nrow=R, dimnames=list(paste("Round",1:R),paste("Player", 1:C)))
M2 <- matrix(0, ncol=C, nrow=R, dimnames=list(paste("Round",1:R),paste("Player", 1:C)))
M3 <- matrix(0, ncol=C, nrow=R, dimnames=list(paste("Round",1:R),paste("Player", 1:C)))
M4 <- matrix(0, ncol=C, nrow=R, dimnames=list(paste("Round",1:R),paste("Player", 1:C)))
M5 <- matrix(0, ncol=C, nrow=R, dimnames=list(paste("Round",1:R),paste("Player", 1:C)))
M6 <- matrix(0, ncol=C, nrow=R, dimnames=list(paste("Round",1:R),paste("Player", 1:C)))
L <- mget(paste0("M", 1:N)) #list of matrices
L

结果如下:

$M1
        Player 1 Player 2
Round 1        0        0
Round 2        0        0
Round 3        0        0

$M2
        Player 1 Player 2
Round 1        0        0
Round 2        0        0
Round 3        0        0

$M3
        Player 1 Player 2
Round 1        0        0
Round 2        0        0
Round 3        0        0

$M4
        Player 1 Player 2
Round 1        0        0
Round 2        0        0
Round 3        0        0

$M5
        Player 1 Player 2
Round 1        0        0
Round 2        0        0
Round 3        0        0

$M6
        Player 1 Player 2
Round 1        0        0
Round 2        0        0
Round 3        0        0

是否有更有效的方法来构建这样的列表 L

2 个答案:

答案 0 :(得分:2)

尝试使用lapply

 setNames(lapply(1:6, function(i) 
       matrix(0, ncol=C, nrow=R, dimnames=list(paste("Round",1:R),
                         paste("Player", 1:C)))), paste0("M", 1:6))

答案 1 :(得分:2)

怎么样:

L <- replicate(10, matrix(0, ncol=C, nrow=R, dimnames=list(paste("Round",1:R),paste("Player", 1:C))), simplify=FALSE)
names(L) <- paste0("M", 1:10)

修改

使用setNames作为@akrun,进一步简化

setNames(replicate(10, matrix(0, ncol=C, nrow=R, dimnames=list(paste("Round",1:R),paste("Player", 1:C))), simplify=FALSE), 
paste0("M", 1:10))