Nathaniel
Nathaniel

Reputation: 131

Terra equivalent for raster::stack()?

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

Upvotes: 12

Views: 15512

Answers (3)

Matifou
Matifou

Reputation: 8880

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

Upvotes: 18

DHenry
DHenry

Reputation: 121

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().

Upvotes: 8

nealmaker
nealmaker

Reputation: 175

I think you want terra::c(). It combines SpatRaster objects, as long as they have the same extent and resolution.

Upvotes: 1

Related Questions