Learn R Programming

terra (version 1.7-55)

terra-package: Description of the methods in the terra package

Description

terra provides methods to manipulate geographic (spatial) data in "raster" and "vector" form. Raster data divide space into rectangular grid cells and they are commonly used to represent spatially continuous phenomena, such as elevation or the weather. Satellite images also have this data structure, and in that context grid cells are often referred to as pixels. In contrast, "vector" spatial data (points, lines, polygons) are typically used to represent discrete spatial entities, such as a road, country, or bus stop.

The package implements two main classes (data types): SpatRaster and SpatVector. SpatRaster supports handling large raster files that cannot be loaded into memory; local, focal, zonal, and global raster operations; polygon, line and point to raster conversion; integration with modeling methods to make spatial predictions; and more. SpatVector supports all types of geometric operations such as intersections.

Additional classes include SpatExtent, which is used to define a spatial extent (bounding box); SpatRasterDataset, which represents a collection of sub-datasets for the same area. Each sub-dataset is a SpatRaster with possibly many layers, and may, for example, represent different weather variables; and SpatRasterCollection and SpatVectorCollection that are equivalent to lists of SpatRaster or SpatVector objects. There is also a SpatGraticule class to assist in adding a longitude/latitude lines and labels to a map with another coordinate reference system.

These classes hold a C++ pointer to the data "reference class" and that creates some limitations. They cannot be recovered from a saved R session either or directly passed to nodes on a computer cluster. Generally, you should use writeRaster to save SpatRaster objects to disk (and pass a filename or cell values to cluster nodes). Also see wrap. Also, package developers should not directly access this pointer, as its user-interface is not stable.

The terra package is conceived as a replacement of the raster package. terra has a very similar, but simpler, interface, and it is faster than raster. At the bottom of this page there is a table that shows differences in the methods between the two packages.

Below is a list of some of the most important methods grouped by theme.

---------------------------------------------------------------------------------------------------------------------

Arguments

<b>SpatRaster</b>

---------------------------------------------------------------------------------------------------------------------

I. Creating, combining and sub-setting

rastCreate a SpatRaster from scratch, file, or another object
cCombine SpatRasters (multiple layers)
add<-Add a SpatRaster to another one
subset or [[, or $Select layers of a SpatRaster
selectRangeSelect cell values from different layers using an index layer
---------------------------------------------------------------------------------------------------------------------

II. Changing the spatial extent or resolution

Also see the methods in section VIII

mergeCombine SpatRasters with different extents (but same origin and resolution)
mosaicCombine SpatRasters with different extents using a function for overlapping cells
cropSelect a geographic subset of a SpatRaster
extendAdd rows and/or columns to a SpatRaster
trimTrim a SpatRaster by removing exterior rows and/or columns that only have NAs
aggregateCombine cells of a SpatRaster to create larger cells
disaggSubdivide cells
resampleResample (warp) values to a SpatRaster with a different origin and/or resolution
projectProject (warp) values to a SpatRaster with a different coordinate reference system
shiftAdjust the location of SpatRaster
flipFlip values horizontally or vertically
rotateRotate values around the date-line (for lon/lat data)
tTranspose a SpatRaster
---------------------------------------------------------------------------------------------------------------------

III. Local (cell based) methods

Apply-like methods

appApply a function to all cells, across layers, typically to summarize (as in base::apply)
tappApply a function to groups of layers (as in base::tapply and stats::aggregate)
lappApply a function to using the layers of a SpatRaster as variables
sappApply a function to each layer
rappApply a function to a spatially variable range of layers
---------------------------------------------------------------------------------------------------------------------

Arithmetic, logical, and standard math methods

Arith-methodsStandard arithmetic methods (+, -, *, ^, %%, %/%, /)
Compare-methodsComparison methods for SpatRaster (==, !=, >, <, <=, >=m is.na, is.finite)
not.naa one-step equivalent to !is.na
Summary-methodsmean, max, min, median, sum, range, prod,
any, all, stdev, which.min, which.max, anyNA, noNA, allNA
Logic-methodsBoolean methods (!, &, |)
Math-methodsabs, sign, sqrt, ceiling, floor, trunc, cummax, cummin, cumprod,
cumsum, log, log10, log2, log1p, acos, acosh, asin, asinh, atan, atanh,
exp, expm1, cos, cosh, sin, sinh, tan, tanh, round, signif
as.boolcreate a Boolean (logical) SpatRaster
as.intcreate an integer (whole numbers) SpatRaster
---------------------------------------------------------------------------------------------------------------------

Other methods

approximateCompute missing values for cells by interpolation across layers
rollRolling functions such as the rolling mean
cellSizeCompute the area of cells
classify(Re-)classify values
substSubstitute (replace) cell values
coverFirst layer covers second layer except where the first layer is NA
initInitialize cells with new values
maskReplace values in a SpatRaster based on values in another SpatRaster
which.lyrwhich is the first layer that is TRUE?
segregateMake a 0/1 layer for each unique value
rangeFillMake a 0/1 SpatRaster for a time series
regressCell-based regression models
---------------------------------------------------------------------------------------------------------------------

IV. Zonal and global methods

expanseCompute the summed area of cells
crosstabCross-tabulate two SpatRasters
freqFrequency table of SpatRaster cell values
globalSummarize SpatRaster cell values with a function
quantileQuantiles
layerCorCorrelation between layers
stretchStretch values
scaleScale values
summarySummary of the values of a SpatRaster (quartiles and mean)
uniqueGet the unique values in a SpatRaster
zonalSummarize a SpatRaster by zones in another SpatRaster
---------------------------------------------------------------------------------------------------------------------

V. Situation (spatial context) based methods

adjacentIdentify cells that are adjacent to a set of cells of a SpatRaster
boundariesDetection of boundaries (edges)
distanceShortest distance to a cell that is not NA or to or from a vector object
gridDistShortest distance through adjacent grid cells
costDistShortest distance considering cell-varying friction
directionDirection (azimuth) to or from cells that are not NA
focalFocal (neighborhood; moving window) functions
focal3DThree dimensional (row, col, lyr) focal functions
focalCppFaster focal by using custom C++ functions
focalRegRegression between layers for focal areas
focalPairsApply a function (e.g. a correlation coefficient) to focal values for pairs of layers
patchesFind patches (clumps)
sieveSieve filter to remove small patches
terrainCompute slope, aspect and other terrain characteristics from elevation data
viewshedCompute viewshed (showing areas that are visible from a particular location
shadeCompute hill shade from slope and aspect layers
autocorCompute global or local spatial autocorrelation
---------------------------------------------------------------------------------------------------------------------

VI. Model predictions

predictPredict a non-spatial model to a SpatRaster
interpolatePredict a spatial model to a SpatRaster
interpIDWInverse-distance-weighted interpolation
interpNearNearest neighbor interpolation
---------------------------------------------------------------------------------------------------------------------

VII. Accessing cell values

Apart from the function listed below, you can also use indexing with [ with cell numbers, and row and/or column numbers

valuescell values (fails with very large rasters)
values<-Set new values to the cells of a SpatRaster
setValuesSet new values to the cells of a SpatRaster
as.matrixGet cell values as a matrix
as.arrayGet cell values as an array
extractExtract cell values from a SpatRaster (with cell numbers, coordinates, points, lines, or polygons)
extractAlongExtract cell values along a line such that the values are in the right order
spatSampleRegular or random sample
minmaxGet the minimum and maximum value of the cells of a SpatRaster (if known)
setMinMaxCompute the minimum and maximum value of a SpatRaster if these are not known
extractspatial queries of a SpatRaster with a SpatVector
---------------------------------------------------------------------------------------------------------------------

VIII. Getting and setting dimensions

Get or set basic parameters of SpatRasters. If there are values associated with a SpatRaster object (either in memory or via a link to a file) these are lost when you change the number of columns or rows or the resolution. This is not the case when the extent is changed (as the number of columns and rows will not be affected). Similarly, with crs you can set the coordinate reference system, but this does not transform the data (see project for that).

ncolThe number of columns
nrowThe number of rows
ncellThe number of cells (can not be set directly, only via ncol or nrow)
resThe resolution (x and y)
nlyrGet or set the number of layers
namesGet or set the layer names
xresThe x resolution (can be set with res)
yresThe y resolution (can be set with res)
xminThe minimum x coordinate (or longitude)
xmaxThe maximum x coordinate (or longitude)
yminThe minimum y coordinate (or latitude)
ymaxThe maximum y coordinate (or latitude)
extGet or set the extent (minimum and maximum x and y coordinates ("bounding box")
originThe origin of a SpatRaster
crsThe coordinate reference system (map projection)
is.lonlatTest if an object has (or may have) a longitude/latitude coordinate reference system
sourcesGet the filename(s) to which a SpatRaster is linked
inMemoryAre the data sources in memory (or on disk)?
compareGeomCompare the geometry of SpatRasters
NAflagSet the NA value (for reading from a file with insufficient metadata)
---------------------------------------------------------------------------------------------------------------------

IX. Computing row, column, cell numbers and coordinates

Cell numbers start at 1 in the upper-left corner. They increase within rows, from left to right, and then row by row from top to bottom. Likewise, row numbers start at 1 at the top of the raster, and column numbers start at 1 at the left side of the raster.

xFromColx-coordinates from column numbers
yFromRowy-coordinates from row numbers
xFromCellx-coordinates from row numbers
yFromCelly-coordinates from cell numbers
xyFromCellx and y coordinates from cell numbers
colFromXColumn numbers from x-coordinates (or longitude)
rowFromYRow numbers from y-coordinates (or latitude)
rowColFromCellRow and column numbers from cell numbers
cellFromXYCell numbers from x and y coordinates
cellFromRowColCell numbers from row and column numbers
cellFromRowColCombineCell numbers from all combinations of row and column numbers
cellsCell numbers from an SpatVector or SpatExtent
---------------------------------------------------------------------------------------------------------------------

X. Time related methods

timeGet or set time
fillTimecan add empty layers in between existing layers to assure that the time step between layers is constant
mergeTimecombine multiple rasters, perhaps partly overlapping in time, into a single time series
---------------------------------------------------------------------------------------------------------------------

XI. Methods for categorical rasters

is.factorAre there categorical layers?
levelsGet active categories, or set categories
activeCatGet or set the active category
catsGet categories (active and inactive)
set.catsSet categories in place
concatsCombine SpatRasters with different categories
catalyzeCreate a layer for each category
as.numericuse the active category to create a non-categorical SpatRaster
as.factorMake the layers of a SpatRaster categorical
---------------------------------------------------------------------------------------------------------------------

XII. Writing SpatRaster files

Basic

writeRasterWrite all values of SpatRaster to disk. You can set the filetype, datatype, compression.
writeCDFWrite SpatRaster data to a netCDF file
---------------------------------------------------------------------------------------------------------------------

Advanced

readStartOpen file connections for efficient multi-chunk reading
readStopClose file connections
writeStartOpen a file for writing
writeValuesWrite some values
writeStopClose the file after writing
blocksGet blocksize for reading files (when not writing)
---------------------------------------------------------------------------------------------------------------------

XIII. Miscellaneous SpatRaster methods

terraOptionsShow, set, or get session options, mostly to control memory use and to set write options
sourcesShow the data sources of a SpatRaster
tmpFilesShow or remove temporary files
mem_infomemory needs and availability
inMemoryAre the cell values in memory?
---------------------------------------------------------------------------------------------------------------------

XIV. SpatRasterDataset

A SpatRasterDataset contains SpatRaster objects that are sub-datasets for the same area. They all have the same extent and resolution.

sdsCreate a SpatRasterDataset from a file with subdatasets (ncdf or hdf) or from SpatRaster objects
[ or $Extract a SpatRaster
namesGet the names of the sub-datasets
---------------------------------------------------------------------------------------------------------------------

XV. SpatRasterCollections

A SpatRasterCollection is a vector of SpatRaster objects. Unlike for a SpatRasterDataset, there the extent and resolution of the SpatRasters do not need to match each other.

sprccreate a SpatRasterCollection from (a list of) SpatRaster objects
lengthhow many SpatRasters does the SpatRasterCollection have?
cropcrop a SpatRasterCollection
imposeforce the members of SpatRasterCollection to the same geometry
mergemerge the members of a SpatRasterCollection
mosaicmosaic (merge with a function for overlapping areas) the members of a SpatRasterCollection
[extract a SpatRaster
---------------------------------------------------------------------------------------------------------------------

<b>SpatVector</b>

---------------------------------------------------------------------------------------------------------------------

XVI. Create SpatVector objects

vectCreate a SpatVector from a file (for example a "shapefile") or from another object
vector_layerslist or delete layers in a vector database such as GPGK
rbindappend SpatVectors of the same geometry type
uniqueremove duplicates
na.omitremove empty geometries and/or fields that are NA
projectProject a SpatVector to a different coordinate reference system
writeVectorWrite SpatVector data to disk
centroidsGet the centroids of a SpatVector
voronoiVoronoi diagram
delaunayDelaunay triangles
convHullCompute the convex hull of a SpatVector
minRectCompute the minimum minimal bounding rotated rectangle of a SpatVector
minCircleCompute the minimal bounding circle of a SpatVector
fillHolesRemove or extract holes from polygons
---------------------------------------------------------------------------------------------------------------------

XVII. Properties of SpatVector objects

geomreturns the geometries as matrix or WKT
crdsreturns the coordinates as a matrix
linearUnitsreturns the linear units of the crs (in meter)
ncolThe number of columns (of the attributes)
nrowThe number of rows (of the geometries and attributes)
namesGet or set the layer names
extGet the extent (minimum and maximum x and y coordinates ("bounding box")
crsThe coordinate reference system (map projection)
is.lonlatTest if an object has (or may have) a longitude/latitude coordinate reference system
---------------------------------------------------------------------------------------------------------------------

XVIII. Geometric queries

adjacentfind adjacent polygons
expansecomputes the area covered by polygons
nearbyfind nearby geometries
nearestfind the nearest geometries
relategeometric relationships such as "intersects", "overlaps", and "touches"
perimcomputes the length of the perimeter of polygons, and the length of lines
---------------------------------------------------------------------------------------------------------------------

XIX. Geometric operations

erase or "-"erase (parts of) geometries
intersect or "*"intersect geometries
union or "+"Merge geometries
coverupdate polygons
symdifsymmetrical difference of two polygons
aggregatedissolve smaller polygons into larger ones
bufferbuffer geometries
disaggsplit multi-geometries into separate geometries
cropclip geometries using a rectangle (SpatExtent) or SpatVector
---------------------------------------------------------------------------------------------------------------------

XX. SpatVector attributes

We use the term "attributes" for the tabular data (data.frame) associated with vector geometries.

extractspatial queries between SpatVector and SpatVector (e.g. point in polygons)
selselect - interactively select geometries
clickidentify attributes by clicking on a map
mergeJoin a table with a SpatVector
as.data.frameget attributes as a data.frame
as.listget attributes as a list
valuesGet the attributes of a SpatVector
values<-Set new attributes to the geometries of a SpatRaster
sortsort SpatVector by the values in a field
---------------------------------------------------------------------------------------------------------------------

XXI. Change geometries (for display, experimentation)

shiftchange the position geometries by shifting their coordinates in horizontal and/or vertical direction
spinrotate geometries around an origin
rescaleshrink (or expand) geometries, for example to make an inset map
flipflip geometries vertically or horizontally
ttranspose geometries (switch x and y)
---------------------------------------------------------------------------------------------------------------------

XXII. Geometry properties and topology

widththe minimum diameter of the geometries
clearancethe minimum clearance of the geometries
sharedPathsshared paths (arcs) between line or polygon geometries
simplifyGeomsimplify geometries
gapsfind gaps between polygon geometries
fillHolesget or remove the polygon holes
makeNodescreate nodes on lines
mergeLinesconnect lines to form polygons
removeDupNodesremove duplicate nodes in geometries and optionally rounds the coordinates
is.validcheck if geometries are valid
makeValidattempt to repair invalid geometries
snapmake boundaries of geometries identical if they are very close to each other
erase (single argument)remove parts of geometries that overlap
union (single argument)create new polygons such that there are no overlapping polygons
rotaterotate to (dis-) connect them across the date-line
normalize.longitudemove geometries that are outside of the -180 to 180 degrees range.
elongatemake lines longer by extending both sides
combineGeomscombine geometries that overlap, share a border, or are within a minimum distance of each other
---------------------------------------------------------------------------------------------------------------------

XXIII. SpatVectorCollections

A SpatVectorCollection is a vector of SpatVector objects.

svccreate a SpatVectorCollection from (a list of) SpatVector objects
lengthhow many SpatRasters does the SpatRasterCollection have?
[extract a SpatVector
---------------------------------------------------------------------------------------------------------------------

<b>Other classes</b>

---------------------------------------------------------------------------------------------------------------------

XXIV. SpatExtent

extCreate a SpatExtent object. For example to crop a Spatial dataset
intersectIntersect two SpatExtent objects, same as -
unionCombine two SpatExtent objects, same as +
Math-methodsround/floor/ceiling of a SpatExtent
alignAlign a SpatExtent with a SpatRaster
drawCreate a SpatExtent by drawing it on top of a map (plot)
---------------------------------------------------------------------------------------------------------------------

XXV. SpatGraticule

graticuleCreate a graticule
cropcrop a graticule
plot<SpatGraticule>plot a graticule
---------------------------------------------------------------------------------------------------------------------

<b>General methods</b>

---------------------------------------------------------------------------------------------------------------------

XXVI. Conversion between spatial data objects from different packages

You can coerce SpatRasters to Raster* objects, after loading the raster package, with as(object, "Raster"), or raster(object) or brick(object) or stack(object)

rastSpatRaster from matrix and other objects
vectSpatVector from sf or Spatial* vector data
sf::st_as_sfsf object from SpatVector
rasterizeRasterizing points, lines or polygons
rasterizeWinRasterize points with a moving window
rasterizeGeomRasterize attributes of geometries such as "count", "area", or "length"
as.pointsCreate points from a SpatRaster or SpatVector
as.linesCreate points from a SpatRaster or SpatVector
as.polygonsCreate polygons from a SpatRaster
as.contourContour lines from a SpatRaster
---------------------------------------------------------------------------------------------------------------------

XXVII. Plotting

Maps

plotPlot a SpatRaster or SpatVector. The main method to create a map
panelCombine multiple plots
pointsAdd points to a map
linesAdd lines to a map
polysAdd polygons to a map
textAdd text (such as the values of a SpatRaster or SpatVector) to a map
haloAdd text with a halo to a map
imageAlternative to plot to make a map with a SpatRaster
plotRGBCombine three layers (red, green, blue channels) into a single "real color" plot
plot<SpatGraticule>plot a graticule
sbarAdd a scale bar to a map
northAdd a north arrow to a map
insetAdd a small inset (overview) map
dotsMake a dot-density map
cartogramMake a cartogram
perspPerspective plot of a SpatRaster
contourContour plot or filled-contour plot of a SpatRaster
colorizeCombine three layers (red, green, blue channels) into a single layer with a color-table
---------------------------------------------------------------------------------------------------------------------

Interacting with a map

zoomZoom in to a part of a map by drawing a bounding box on it
clickQuery values of SpatRaster or SpatVector by clicking on a map
selSelect a spatial subset of a SpatRaster or SpatVector by drawing on a map
drawCreate a SpatExtent or SpatVector by drawing on a map
---------------------------------------------------------------------------------------------------------------------

Other plots

plotx-y scatter plot of the values of (a sample of) the layers of two SpatRaster objects
histHistogram of SpatRaster values
barplotBar plot of a SpatRaster
densityDensity plot of SpatRaster values
pairsPairs plot for layers in a SpatRaster
boxplotBox plot of the values of a SpatRaster
---------------------------------------------------------------------------------------------------------------------

<b>Comparison with the raster package</b>

---------------------------------------------------------------------------------------------------------------------

XXVIII. New method names

terra has a single class SpatRaster for which raster has three (RasterLayer, RasterStack, RasterBrick). Likewise there is a single class for vector data SpatVector that replaces six Spatial* classes. Most method names are the same, but note the following important differences in methods names with the raster package

raster packageterra package
raster, brick, stackrast
rasterFromXYZrast( , type="xyz")
stack, addLayerc
addLayeradd<-
areacellSize or expanse
approxNAapproximate
calcapp
cellFromLine, cellFromPolygon,cells
cellsFromExtentcells
cellStatsglobal
clumppatches
compareRastercompareGeom
corLocalfocalPairs
coordinatescrds
couldBeLonLatis.lonlat
disaggregatedisagg
distanceFromPointsdistance
drawExtent, drawPoly, drawLinedraw
dropLayersubset
extentext
getValuesvalues
isLonLat, isGlobalLonLatis.lonlat
layerizesegregate
layerStatslayerCor
movingFunroll
NAvalueNAflag
nlayersnlyr
overlaylapp
unstackas.list
projectRasterproject
rasterToPointsas.points
rasterToPolygonsas.polygons
reclassify, subs, cutclassify
sampleRandom, sampleRegularspatSample
shapefilevect
stackApplytapp
stackSelectselectRange

XXIX. Changed behavior

Also note that even if function names are the same in terra and raster, their output can be different. In most cases this was done to get more consistency in the returned values (and thus fewer errors in the downstream code that uses them). In other cases it simply seemed better. Here are some examples:

as.polygonsBy default, terra returns dissolved polygons
quantilecomputes by cell, across layers instead of the other way around
extractBy default, terra returns a matrix, with the first column the sequential ID of the vectors.
raster returns a list (for lines or polygons) or a matrix (for points, but without the ID
column. You can use list=TRUE to get the results as a list
valuesterra always returns a matrix. raster returns a vector for a RasterLayer
Summary-methodsWith raster, mean(x, y) and mean(stack(x, y) return the same result, a single
layer with the mean of all cell values. This is also what terra returns with
mean(c(x, y)), but with mean(x, y) the parallel mean is returned -- that is, the
computation is done layer-wise, and the number of layers in the output is the same as
that of x and y (or the larger of the two if they are not the same). This affects
all summary functions (sum, mean, median, which.min, which.max, min, max,
prod, any, all, stdev), except range, which is not implemented for this case
(you can use min and max instead)
---------------------------------------------------------------------------------------------------------------------

Authors

Except where indicated otherwise, the methods and functions in this package were written by Robert Hijmans. The configuration scripts were written by Roger Bivand. Some of code using the GEOS library was adapted from code by Edzer Pebesma for sf. Michael Sumner contributed various bits and pieces.

Acknowledgments

This package is an attempt to climb on the shoulders of giants (GDAL, PROJ, GEOS, NCDF, GeographicLib, Rcpp, R). Many people have contributed by asking questions or raising issues. Feedback and suggestions by Márcia Barbosa, Kendon Bell, Andrew Gene Brown, Jean-Luc Dupouey, Krzysztof Dyba, Sarah Endicott, Alex Ilich, Gerald Nelson, Jakub Nowosad, and Monika Tomaszewska have been especially helpful.