How to create a simple raster in R terra

66 Views Asked by At

looking at the help file creating a raster in terra is pretty similar to raster, however, I keep getting an 'empty srs' error (for other operations in terra also).

What is srs? It seems to be the same as crs? why the name change?

library(raster)

d <- raster(xmn=1, xmx=17, ymn=46, ymx=57, nrows=1320, ncols = 960, vals = 1, crs = 4326)

library(terra)

d <- rast(xmin=1, xmax=17, ymin=46, ymax=57, nrows=1320, ncols = 960, vals = 1, crs = 4326)
2

There are 2 best solutions below

2
Robert Hijmans On

This makes no sense:

library(terra)
# terra 1.7.71
d <- rast(crs = 4326)
# Error: [rast] empty srs

Because the number 4326 is not a spatial/coordinate reference system. I agree that the error message is not especially helpful.

Presumably, you want to use that EPSG code. In that case you can do

d <- rast(crs = "EPSG:4326")
d
#class       : SpatRaster 
#dimensions  : 180, 360, 1  (nrow, ncol, nlyr)
#resolution  : 1, 1  (x, y)
#extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
#coord. ref. : lon/lat WGS 84 (EPSG:4326) 

You probably thought you could use crs = 4326 because the equivalent is valid with the "sf" package. The reasons to require the ESPG prefix are that (1) it is not the only coding system (e.g. ESRI:) and (2) it much improves the readability of the code: a single number to an entry in an unspecified database is a very opaque reference.

You can also use the more descriptive PROJ notation:

d <- rast(crs = "+proj=longlat")
1
Blaiso On

The answer for using terra is:

library(terra)

d <- rast(xmin=1, xmax=17, ymin=46, ymax=57, nrows=1320, ncols = 960, vals = 1, crs = "espg:4326")

I would recommend using the raster package though.