Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to I seperate a SpatRaster into multiple layers in terra?

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.

like image 293
Chris Stantis Avatar asked Dec 15 '25 06:12

Chris Stantis


1 Answers

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

like image 138
margusl Avatar answered Dec 16 '25 22:12

margusl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!