0

can I simplify this using a loop? I need to make over 50 of them and I am currently doing it manually (e.g., r, r1, r2, r3, r4 ...).

Is there a way I can do all 50 in a simpler code?

r   <- raster(extent(-180, 180, -90, 90), ncols = 150, nrows = 80)
r1  <- raster(extent(-180, 180, -90, 90), ncols = 150, nrows = 80)
r2  <- raster(extent(-180, 180, -90, 90), ncols = 150, nrows = 80)
L55
  • 117
  • 8

1 Answers1

1

You can map the function assign on a sequence:

library(raster)
library(purrr)

my_raster <- raster(extent(-180, 180, -90, 90), ncols = 150, nrows = 80)

seq(50) %>% 
  walk(~ assign(x = paste0("r", .x), my_raster, envir = globalenv()))

Please keep in mind that this will mess up your global environment quite much. It is much cleaner to group the rasters into one list:

my_rasters <-
  seq(50) %>%
  map(~ paste0("my_raster_", .x)) %>%
  set_names() %>%
  map(~my_raster)

# access one raster
my_rasters$my_raster_23
danlooo
  • 10,067
  • 2
  • 8
  • 22
  • what do you mean by ```list```? what does envir = globalenv() do? I tried to look it up but there is this discussion that says not to use it? https://stackoverflow.com/questions/9726705/assign-multiple-objects-to-globalenv-from-within-a-function – L55 Dec 08 '21 at 10:22
  • Values are stored in buckets called environments. If you need to access them from everywhere without defining the env explicitly, you need to create them in the global env. I added a statement about messyness in my answer. Creating global vars will have side effects so things get complicated. – danlooo Dec 08 '21 at 10:25
  • how do I group them by ```list```? is this different? – L55 Dec 08 '21 at 10:26
  • Use `map` instead of `walk`: `my_rasters <- seq(50) %>% map(~ my_raster)` Note that the function `rep` only works for S3 objects. – danlooo Dec 08 '21 at 10:28
  • is it possible to rename them so the output is my_raster1, my_raster_2 etc. this comes as [[1]] – L55 Dec 08 '21 at 10:40
  • @L55 Yes: I updated my answer accordingly. – danlooo Dec 08 '21 at 10:43