Search code examples
rlistmatrixpastedimensions

Create a list of multiple identical (same dimension) matrices in R


I am creating N number of matrices (M1, M2, ... Mn) of the same size (C x R) and store them in the list L.

My code is the following:

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

The results look like this:

$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

Is there a more efficient way to build such a list L?


Solution

  • What about:

    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)
    

    edit

    use setNames as @akrun did, to simplify further

    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))