Reputation: 764
I would like to create 18
null matrices of the same dimension named as 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.
Upvotes: 2
Views: 202
Reputation: 887481
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
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)
Upvotes: 0
Reputation: 160577
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. This is the same approach as a "list of frames", see 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
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
Upvotes: 5
Reputation: 1300
Try assign
:
for( s in seq(10,95,by=5)){
assign (paste0("mat",s,"ci"), array(NA, dim = c(10, 20)))
}
Upvotes: 1
Reputation: 102201
Maybe you can try 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()
[1] "mat10ci" "mat15ci" "mat20ci" "mat25ci" "mat30ci" "mat35ci" "mat40ci"
[8] "mat45ci" "mat50ci" "mat55ci" "mat60ci" "mat65ci" "mat70ci" "mat75ci"
[15] "mat80ci" "mat85ci" "mat90ci" "mat95ci"
Upvotes: 2