Home > Net >  Assigning value to list elements in for loop, list names depending on loop
Assigning value to list elements in for loop, list names depending on loop

Time:01-07

I have the following problem. I am working with two for loops (running over i and j) and use the assign function to create lists whose names depend on i and j. Now, in another for loop withing the two loops, i want to fill my created lists with rasters, namely 19 rasters. However, I am failing to call my lists as they depend on i and j, thus, I am not able to fill them.

At the end, I would like to have 25 lists carrying the names rasterList_10N_010E, rasterList_20N_010E,... that each have 19 entries with the respective rasters.

Below you find my code. I have dropped lines not important for my problem (I actually generate the rasters I want to store in my lists depending on i and j within the loops, too).

for(i in 1:5){
for(j in 1:5){
nam <- paste0("rasterList_", i*10, "N_0", j*10, "E") 
assign(nam, list())    

  for (k in 1:19){
     raster_test <- raster(ncol=36, nrow=18, xmn=-1000, xmx=1000, ymn=-100, ymx=900)
    #here the list with the name nam should be standing
    rasterList_10N_010E[[k]] <- raster_test
      }
    }
  }

I have tried solutions using

eval(as.name(nam))[[k]] <- raster_test

and

as.name(nam)[[k]] <- raster_test

but it did not work. I believe that the problem may be that the approach is not very R-like (I have just recently changed from Stata to R)?

Thanks!

CodePudding user response:

Instead of creating 25 single lists I would suggest to put your lists into one list like so:

Note: I have set k = 2 for simplicity.

library(raster)
#> Loading required package: sp

rasterList <- list()

for (i in 1:5) {
  for (j in 1:5) {
    name <- paste0(i * 10, "N_0", j * 10, "E")
    rasterList[[name]] <- list()
    for (k in 1:2) {
      raster_test <- raster(ncol = 36, nrow = 18, xmn = -1000, xmx = 1000, ymn = -100, ymx = 900)
      rasterList[[name]][k] <- raster_test
    }
  }
}

length(rasterList)
#> [1] 25

rasterList[["10N_010E"]]
#> [[1]]
#> class      : RasterLayer 
#> dimensions : 18, 36, 648  (nrow, ncol, ncell)
#> resolution : 55.55556, 55.55556  (x, y)
#> extent     : -1000, 1000, -100, 900  (xmin, xmax, ymin, ymax)
#> crs        : NA 
#> 
#> 
#> [[2]]
#> class      : RasterLayer 
#> dimensions : 18, 36, 648  (nrow, ncol, ncell)
#> resolution : 55.55556, 55.55556  (x, y)
#> extent     : -1000, 1000, -100, 900  (xmin, xmax, ymin, ymax)
#> crs        : NA

And if still necessary you could get your 25 lists afterwards like so:

lapply(names(rasterList), function(x) assign(paste0("rasterList_", x), rasterList[[x]], envir = .GlobalEnv))

Created on 2022-01-05 by the reprex package (v2.0.1)

  •  Tags:  
  • Related