Home > OS >  Stack / concatenate rasters in a list (terra - spatRaster)
Stack / concatenate rasters in a list (terra - spatRaster)

Time:07-13

I want to stack a few rasters I have in a list using terra.

This used to work very easily in raster because it was possible to stack() the list. However, this is not possible anymore in terra. See the example below:

r1 <- raster(nrows = 1, ncols = 1, res = 0.5, xmn = -1.5, xmx = 1.5, ymn = -1.5, ymx = 1.5, vals = 0.1)
r2 <- raster(nrows = 1, ncols = 1, res = 0.5, xmn = -1.5, xmx = 1.5, ymn = -1.5, ymx = 1.5, vals = 0.2)
r_list <- list(r1, r2)
r_stack <- stack(r_list)

Resuls in a raster stack:

class      : RasterStack 
dimensions : 6, 6, 36, 2  (nrow, ncol, ncell, nlayers)
resolution : 0.5, 0.5  (x, y)
extent     : -1.5, 1.5, -1.5, 1.5  (xmin, xmax, ymin, ymax)
crs        :  proj=longlat  datum=WGS84  no_defs 
names      : layer.1, layer.2 
min values :     0.1,     0.2 
max values :     0.1,     0.2 

But the equivalent in terra, using c(), does not work directly on the list:

r1 <- rast(nrows = 1, ncols = 1, resolution = 0.5, xmin = -1.5, xmax = 1.5, ymin = -1.5, ymax = 1.5, vals = 0.1)
r2 <- rast(nrows = 1, ncols = 1, resolution = 0.5, xmin = -1.5, xmax = 1.5, ymin = -1.5, ymax = 1.5, vals = 0.2)
r_list <- list(r1, r2)
r_c <- c(r_list)

The error is this:

Error in .local(x, ...) : Arguments should be Raster* objects or filenames

Is there a workaround to stack spatRaster in a list?

CodePudding user response:

You can use the following code to convert the list to a stacked raster using terra package

library(terra)

r1 <- rast(nrows = 1, ncols = 1, resolution = 0.5, xmin = -1.5, xmax = 1.5, ymin = -1.5, ymax = 1.5, vals = 0.1)
r2 <- rast(nrows = 1, ncols = 1, resolution = 0.5, xmin = -1.5, xmax = 1.5, ymin = -1.5, ymax = 1.5, vals = 0.2)
r_list <- list(r1, r2)
r_c <- rast(r_list) 

which gives you

class       : SpatRaster 
dimensions  : 6, 6, 2  (nrow, ncol, nlyr)
resolution  : 0.5, 0.5  (x, y)
extent      : -1.5, 1.5, -1.5, 1.5  (xmin, xmax, ymin, ymax)
coord. ref. : lon/lat WGS 84 
sources     : memory  
              memory  
names       : lyr.1, lyr.1 
min values  :   0.1,   0.2 
max values  :   0.1,   0.2 

Or you can use the following

r1 <- rast(nrows = 1, ncols = 1, resolution = 0.5, xmin = -1.5, xmax = 1.5, ymin = -1.5, ymax = 1.5, vals = 0.1)
r2 <- rast(nrows = 1, ncols = 1, resolution = 0.5, xmin = -1.5, xmax = 1.5, ymin = -1.5, ymax = 1.5, vals = 0.2)

r_c <- c(r1, r2)
  • Related