r,terra – How to Import DEM with R Terra Package from a List Containing Two Elements

rterra

Using an example from Geocomputations in R, I'm trying to import a DEM (from RSAGA package) from a 2-element file (header and list of elevations).

It works with the Raster package, but I'm having trouble with the proper syntax for Terra. I get an error indicating unused arguments in the code below. Could someone please check the Terra syntax and advise what the correct code would be?

# example from Geocomputations in R (v.1)
library(raster)
library(terra)
data("landslides", package = "RSAGA")

# this works:
demRaster <- raster::raster(dem$data,
                            crs = dem$header$proj4string,
                            xmn = dem$header$xllcorner,
                            xmx = dem$header$xllcorner + dem$header$ncols * dem$header$cellsize,
                            ymn = dem$header$yllcorner,
                            ymx = dem$header$yllcorner + dem$header$nrows * dem$header$cellsize)
# unused arguments error:
demTerra <- terra::rast(dem$data,
                        nrows = dem$header$nrows,
                        ncols = dem$header$ncols,
                        nlyrs = 1,
                        xmin  = dem$header$xllcorner,
                        xmax  = dem$header$xllcorner + dem$header$ncols * dem$header$cellsize,
                        ymin  = dem$header$yllcorner,
                        ymax  = dem$header$yllcorner + dem$header$nrows * dem$header$cellsize,
                        crs   = dem$header$proj4string)

Best Answer

I had the same issue some time ago and fortunately this is quite easy to fix.

Since dem$data is a matrix, terra::rast() does only accept a few number of arguments:

library(raster)
library(terra)
#> terra 1.6.33

data("landslides", package = "RSAGA")

class(dem$data)
#> [1] "matrix" "array"

According to ?rast, you are only able to pass the following attributes:

## S4 method for signature 'matrix'
rast(x, type="", crs="", digits=6, extent=NULL)

So basically, all you need to do is to create an object of type SpatExtent from your xmin, xmax, ymin, ymax coordinates and pass this along with the crs:

e <- ext(dem$header$xllcorner,
         dem$header$xllcorner + dem$header$ncols * dem$header$cellsize,
         dem$header$yllcorner,
         dem$header$yllcorner + dem$header$nrows * dem$header$cellsize)

r <- terra::rast(dem$data,
                 crs = dem$header$proj4string,
                 extent = e)

r
#> class       : SpatRaster 
#> dimensions  : 415, 383, 1  (nrow, ncol, nlyr)
#> resolution  : 10, 10  (x, y)
#> extent      : 711962.7, 715792.7, 9556862, 9561012  (xmin, xmax, ymin, ymax)
#> coord. ref. : +proj=utm +zone=17 +south +datum=WGS84 +units=m +no_defs 
#> source(s)   : memory
#> name        :    lyr.1 
#> min value   : 1711.204 
#> max value   : 3164.165