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 useassign()to store each of those layers in a new object: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.
Created on 2023-08-19 with reprex v2.0.2