2

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.

Uddin
  • 658
  • 2
  • 11
  • 1
    If you're going to deal with multiple matrices in the same way, I strongly suggest you put them in a `list`, very similar to the [list of frames](https://stackoverflow.com/a/24376207/3358272) discussion. For instance, `lst_of_mtx – r2evans Sep 12 '20 at 20:20
  • Or frankly, you could deal with it as a single 3d array, as in `array(dim=c(10, 20, 18))`. – r2evans Sep 12 '20 at 20:21

4 Answers4

5

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
r2evans
  • 77,184
  • 4
  • 55
  • 96
3

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"
ThomasIsCoding
  • 53,240
  • 4
  • 13
  • 45
1

Try assign :

for( s in seq(10,95,by=5)){
  assign (paste0("mat",s,"ci"), array(NA, dim = c(10, 20)))
}
Liman
  • 897
  • 4
  • 9
1

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)
akrun
  • 674,427
  • 24
  • 381
  • 486