[英]How to create multiple null matrices in R?
I would like to create 18
null matrices of the same dimension named as mat10ci
, mat15ci
,...., mat95ci
.我想创建18
相同维度的空矩阵,命名为mat10ci
, mat15ci
,...., mat95ci
。 I have tried the following code我试过下面的代码
for( s in seq(10,95,by=5)){
paste0("mat",s,"ci")=array(NA, dim = c(10, 20))
}
I am having this error我有这个错误
target of assignment expands to non-language object
Help is appreciated.帮助表示赞赏。
I'm inferring that you're going to be doing the same (or very similar) things to each matrix, in which case the R-idiomatic way to deal with this is to keep them together in a list of matrices.我推断您将对每个矩阵执行相同(或非常相似)的操作,在这种情况下,处理此问题的 R 惯用方法是将它们放在一个矩阵列表中。 This is the same approach as a "list of frames", see https://stackoverflow.com/a/24376207/3358272 .这与“帧列表”的方法相同,请参阅https://stackoverflow.com/a/24376207/3358272 。
For a list of matrices, try:对于矩阵列表,请尝试:
lst_of_mtx <- replicate(18, array(dim = c(10, 20)), simplify = FALSE)
As an alternative, depending on your processing, you could do a single 3d array作为替代方案,根据您的处理,您可以执行单个 3d 数组
ary <- array(dim=2:4, dimnames=list(NULL,NULL,paste0("mat", c(10, 15, 20, 25), "ci")))
ary
# , , mat10ci
# [,1] [,2] [,3]
# [1,] NA NA NA
# [2,] NA NA NA
# , , mat15ci
# [,1] [,2] [,3]
# [1,] NA NA NA
# [2,] NA NA NA
# , , mat20ci
# [,1] [,2] [,3]
# [1,] NA NA NA
# [2,] NA NA NA
# , , mat25ci
# [,1] [,2] [,3]
# [1,] NA NA NA
# [2,] NA NA NA
where you can deal with just one "slice" of the array as在那里你可以只处理数组的一个“切片”
ary[,,"mat25ci"]
# [,1] [,2] [,3]
# [1,] NA NA NA
# [2,] NA NA NA
Maybe you can try list2env
+ replicate
也许你可以试试list2env
+ replicate
list2env(
setNames(
replicate(18, array(NA, dim = c(10, 20)), simplify = FALSE),
paste0("mat", seq(10, 95, by = 5), "ci")
),
envir = .GlobalEnv
)
When you type ls()
, you will see当你输入ls()
,你会看到
> ls()
[1] "mat10ci" "mat15ci" "mat20ci" "mat25ci" "mat30ci" "mat35ci" "mat40ci"
[8] "mat45ci" "mat50ci" "mat55ci" "mat60ci" "mat65ci" "mat70ci" "mat75ci"
[15] "mat80ci" "mat85ci" "mat90ci" "mat95ci"
Try assign
:尝试assign
:
for( s in seq(10,95,by=5)){
assign (paste0("mat",s,"ci"), array(NA, dim = c(10, 20)))
}
We can also do我们也可以做
lst1 <- vector('list', 18)
names(lst1) <- paste0("mat", seq(10, 95, by = 5), "ci")
for(nm in names(lst1)) {
lst1[[nm]] <- array(dim c(10, 20))
}
list2env(lst1, .GlobalEnv)
Or an option with tidyverse
using rerun
或者使用rerun
tidyverse
选项
library(dplyr)
library(purrr)
library(stringr)
18 %>%
rerun(array(dim = c(10, 20))) %>%
set_names(str_c("mat", seq(10, 95, by = 5), "ci")) %>%
list2env(.GlobalEnv)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.