I've applied a function to create a multi-layer SpatRaster using terra. It's worked find, but now I'd like to separate each layer and name the new SpatRaster after the layer name. For three layers it's not so bad, but I'm looking at 15-100 layers later. How can I write a for-loop or other solution to automate this?
I'm terrible at R for loops but I suspect they can come to my rescue.
library(terra)
#create example layered raster
a <- rast(ncol = 10, nrow = 10)
values(a) <- rep(5,100)
names(a) <- "layer_one"
b <- rast(ncol = 10, nrow = 10)
values(b) <- rep(10,100)
names(b) <- "layer_two"
c <- rast(ncol = 10, nrow = 10)
values(c) <- rep(15,100)
names(c) <- "layer_three"
z <- c(a,b,c)
ids <- names(z)
In this example, I'd like three SpatRasters, layer_one, layer_two, layer_three.
You could cycle though names()
and use assign()
to store each of those layers in a new object:
library(terra)
z <- c(a,b,c)
for(lyr in names(z)) assign(lyr, z[[lyr]])
# list layer_* objects
ls(pattern = "layer_.*")
#> [1] "layer_one" "layer_three" "layer_two"
layer_one
#> class : SpatRaster
#> dimensions : 10, 10, 1 (nrow, ncol, nlyr)
#> resolution : 36, 18 (x, y)
#> extent : -180, 180, -90, 90 (xmin, xmax, ymin, ymax)
#> coord. ref. : lon/lat WGS 84
#> source(s) : memory
#> name : layer_one
#> min value : 5
#> max value : 5
Just a thought, but having SpatRasterDataset(s) or just a list of SpatRasters sounds like a more manageable approach than having tens of terra objects in a global environment.
# a list:
rast_list <- split(z, 1:nlyr(z)) |> `names<-`(names(z))
str(rast_list)
#> List of 3
#> $ layer_one :S4 class 'SpatRaster' [package "terra"]
#> $ layer_two :S4 class 'SpatRaster' [package "terra"]
#> $ layer_three:S4 class 'SpatRaster' [package "terra"]
rast_list$layer_one
#> class : SpatRaster
#> dimensions : 10, 10, 1 (nrow, ncol, nlyr)
#> resolution : 36, 18 (x, y)
#> extent : -180, 180, -90, 90 (xmin, xmax, ymin, ymax)
#> coord. ref. : lon/lat WGS 84
#> source(s) : memory
#> name : layer_one
#> min value : 5
#> max value : 5
# list to SpatRasterDataset:
rast_ds <- sds(rast_list)
rast_ds
#> class : SpatRasterDataset
#> subdatasets : 3
#> dimensions : 10, 10 (nrow, ncol)
#> nlyr : 1, 1, 1
#> resolution : 36, 18 (x, y)
#> extent : -180, 180, -90, 90 (xmin, xmax, ymin, ymax)
#> coord. ref. : lon/lat WGS 84
#> source(s) : memory
#> names : layer_one, layer_two, layer_three
Created on 2023-08-19 with reprex v2.0.2