1 The Basics
This section covers an overview of the terra package, as well as the basics for getting geospatial data in and out of R using terra.
1.1 A bird’s eye view
The terra package looks like what would happen if the authors of raster got frustrated with maintaining a package whose scope had ballooned massively over its 10+ year history, and decided to start from scratch to create a newer, better geospatial package.
Because that is in fact what happened.
Terra in a nutshell:
- Raster AND vector support
- Fewer classes, more functionality
- One task, one function
- Written in C++ for improved speed
- Very large: 345 functions; raster has 277, sf has 150
- Some things changed, many stayed the same
Old Packages: sp, raster, rgdal, rgeos, maptools
New Packages: terra, geodata, and tidyterra (for plotting)
1.2 Classes
The terra package condenses the number of classes necessary for analysis from 10 down to 3: one for rasters, one for vectors, and one for extents.
1.3 Reading in data
The raster constructor method, rast
, changed quite a bit
from raster, at least in part because it is a combination of three
previous functions: raster
, brick
and stack
. Most of the
existing arguments are renamed, and some new ones added, including the
ability to specify a timestamp and units for each layer of an empty raster.
Additionally rast
and vect
, the vector constructor method, provide data
filtering built in. They both allow layer selection and spatial filtering and
vect
allows SQL queries from spatial databases as well.
#import elevation data for Luxembourg
elev = rast(elev_fn, , lyrs=1)
#import polygons for cantons of the district of Diekirch
lux = vect(lux_fn)
Terra speeds up reading in both raster an vector data. This is due to C++ implementation of the classes, which imposes some limitations. Most significantly for reading in data, spatRasters and spatVectors cannnot be recovered from a saved R session. However, using saved R sessions is not a good (reproducible) practice anyway, so consider this a feature not a bug.
Reading and writing data functionality is still based on GDAL, so you will have all the flexibility in your choice of file type that GDAL provides, but will have to deal with the issues that using GDAL generates.
1.4 Writing data
The function writeRaster
is relatively unchanged, though the
argument specifying the type of file written has changed from format
(in raster) to filetype
(in terra). Additionally, while in theory the
function can automatically detect the file type, it seems to rarely
work, so it is better to just specify filetype
from the get-go.
For spatVectors we get writeVector
, which largely mirrors
writeRaster
.