Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terra equivalent for raster::stack()?

Tags:

r

gis

raster

terra

Basically the title. I know you can read in a folder of rasters with rast() but I just want to stack two rasters that are read in separately. Thanks

like image 373
Nathaniel Avatar asked Jan 22 '26 17:01

Nathaniel


2 Answers

Note that with raster::stack, you were able to use it either on multiple arguments (stack(x1,x2,x3)) or on a list (stack(list(x1,x2, x3))).

This is no longer true with terra's c. You need to differentiate:

  • use c(x1, x2, x3) when providing separate arguments
  • use rast(list(x1,x2,x3)) when providing the arguments as a list.
library(terra)
#> terra 1.5.21

x <- rast(xmin=-110, xmax=-80, ymin=40, ymax=70, ncols=30, nrows=30)
values(x) <- 1:ncell(x)

many_rasters <- list(x,x)

## this works
rast( many_rasters)
#> class       : SpatRaster 
#> dimensions  : 30, 30, 2  (nrow, ncol, nlyr)
#> resolution  : 1, 1  (x, y)
#> extent      : -110, -80, 40, 70  (xmin, xmax, ymin, ymax)
#> coord. ref. : lon/lat WGS 84 
#> sources     : memory  
#>               memory  
#> names       : lyr.1, lyr.1 
#> min values  :     1,     1 
#> max values  :   900,   900

## just using c creates a list
c(many_rasters)
#> [[1]]
#> class       : SpatRaster 
#> dimensions  : 30, 30, 1  (nrow, ncol, nlyr)
#> resolution  : 1, 1  (x, y)
#> extent      : -110, -80, 40, 70  (xmin, xmax, ymin, ymax)
#> coord. ref. : lon/lat WGS 84 
#> source      : memory 
#> name        : lyr.1 
#> min value   :     1 
#> max value   :   900 
#> 
#> [[2]]
#> class       : SpatRaster 
#> dimensions  : 30, 30, 1  (nrow, ncol, nlyr)
#> resolution  : 1, 1  (x, y)
#> extent      : -110, -80, 40, 70  (xmin, xmax, ymin, ymax)
#> coord. ref. : lon/lat WGS 84 
#> source      : memory 
#> name        : lyr.1 
#> min value   :     1 
#> max value   :   900
like image 71
Matifou Avatar answered Jan 25 '26 08:01

Matifou


For future users with this question note that terra::c() returns

Error: 'c' is not an exported object from 'namespace:terra'

To stack rasters in terra you can simply use base c().

like image 44
DHenry Avatar answered Jan 25 '26 07:01

DHenry



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!