[英]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 . 我正在创建N个相同大小( C x R )的矩阵 ( M1,M2,... Mn ),并将它们存储在列表 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 ? 有没有更有效的方法来建立这样的列表L ?
Try using lapply
尝试使用
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))
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)
use setNames
as @akrun did, to simplify further 与@akrun一样使用
setNames
,以进一步简化
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.