`terra-package.Rd`

`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`

.

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.

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

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

`rast` | Create a SpatRaster from scratch, file, or another object |

`c` | Combine SpatRasters (multiple layers) |

`add<-` | Add a SpatRaster to another one |

`subset` or `[[` , or `$` | Select layers of a SpatRaster |

`selectRange` | Select cell values from different layers using an index layer |

--------------------------- | ------------------------------------------------------------------------------------------ |

Also see the methods in section VIII

`merge` | Combine SpatRasters with different extents (but same origin and resolution) |

`mosaic` | Combine SpatRasters with different extents using a function for overlapping cells |

`crop` | Select a geographic subset of a SpatRaster |

`extend` | Add rows and/or columns to a SpatRaster |

`trim` | Trim a SpatRaster by removing exterior rows and/or columns that only have NAs |

`aggregate` | Combine cells of a SpatRaster to create larger cells |

`disagg` | Subdivide cells |

`resample` | Resample (warp) values to a SpatRaster with a different origin and/or resolution |

`project` | Project (warp) values to a SpatRaster with a different coordinate reference system |

`shift` | Adjust the location of SpatRaster |

`flip` | Flip values horizontally or vertically |

`rotate` | Rotate values around the date-line (for lon/lat data) |

`t` | Transpose a SpatRaster |

--------------------------- | ------------------------------------------------------------------------------------------ |

`app` | Apply a function to all cells, across layers, typically to summarize (as in `base::apply` ) |

`tapp` | Apply a function to groups of layers (as in `base::tapply` and `stats::aggregate` ) |

`lapp` | Apply a function to using the layers of a SpatRaster as variables |

`sapp` | Apply a function to each layer |

`rapp` | Apply a function to a spatially variable range of layers |

--------------------------- | ------------------------------------------------------------------------------------------ |

`Arith-methods` | Standard arithmetic methods (`+, -, *, ^, %%, %/%, /` ) |

`Compare-methods` | Comparison methods for SpatRaster (`==, !=, >, <, <=, >=m is.na, is.finite` ) |

`not.na` | a one-step equivalent to `!is.na` |

`Summary-methods` | `mean, max, min, median, sum, range, prod,` |

`any, all, stdev, which.min, which.max, anyNA, noNA, allNA` | |

`Logic-methods` | Boolean methods (`!, &, |` ) |

`Math-methods` | `abs, 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.bool` | create a Boolean (logical) SpatRaster |

`as.int` | create an integer (whole numbers) SpatRaster |

--------------------------- | ------------------------------------------------------------------------------------------ |

`approximate` | Compute missing values for cells by interpolation across layers |

`roll` | Rolling functions such as the rolling mean |

`cellSize` | Compute the area of cells |

`classify` | (Re-)classify values |

`subst` | Substitute (replace) cell values |

`cover` | First layer covers second layer except where the first layer is `NA` |

`init` | Initialize cells with new values |

`mask` | Replace values in a SpatRaster based on values in another SpatRaster |

`which.lyr` | which is the first layer that is `TRUE` ? |

`segregate` | Make a 0/1 layer for each unique value |

`rangeFill` | Make a 0/1 SpatRaster for a time series |

--------------------------- | ------------------------------------------------------------------------------------------ |

`expanse` | Compute the summed area of cells |

`crosstab` | Cross-tabulate two SpatRasters |

`freq` | Frequency table of SpatRaster cell values |

`global` | Summarize SpatRaster cell values with a function |

`quantile` | Quantiles |

`layerCor` | Correlation between layers |

`stretch` | Stretch values |

`scale` | Scale values |

`summary` | Summary of the values of a SpatRaster (quartiles and mean) |

`unique` | Get the unique values in a SpatRaster |

`zonal` | Summarize a SpatRaster by zones in another SpatRaster |

--------------------------- | ------------------------------------------------------------------------------------------ |

`adjacent` | Identify cells that are adjacent to a set of cells of a SpatRaster |

`boundaries` | Detection of boundaries (edges) |

`distance` | Shortest distance to a cell that is not `NA` or to or from a vector object |

`gridDist` | Shortest distance through adjacent grid cells |

`costDist` | Shortest distance considering cell-varying friction |

`direction` | Direction (azimuth) to or from cells that are not `NA` |

`focal` | Focal (neighborhood; moving window) functions |

`focal3D` | Three dimensional (row, col, lyr) focal functions |

`focalCpp` | Faster focal by using custom C++ functions |

`focalReg` | Regression between layers for focal areas |

`focalPairs` | Apply a function (e.g. a correlation coeffient) to focal values for pairs of layers |

`patches` | Find patches (clumps) |

`sieve` | Sieve filter to remove small patches |

`terrain` | Compute slope, aspect and other terrain characteristics from elevation data |

`viewshed` | Compute vieshed (showing areas that are visible from a particular location |

`shade` | Compute hill shade from slope and aspect layers |

`autocor` | Compute global or local spatial autocorrelation |

--------------------------- | ------------------------------------------------------------------------------------------ |

`predict` | Predict a non-spatial model to a SpatRaster |

`interpolate` | Predict a spatial model to a SpatRaster |

`interpIDW` | Inverse-distance-weighted interpolation |

`interpNear` | Nearst neighbor interpolation |

--------------------------- | ------------------------------------------------------------------------------------------ |

Apart from the function listed below, you can also use indexing with `[`

with cell numbers, and row and/or column numbers

`values` | cell values (fails with very large rasters) |

`values<-` | Set new values to the cells of a SpatRaster |

`setValues` | Set new values to the cells of a SpatRaster |

`as.matrix` | Get cell values as a matrix |

`as.array` | Get cell values as an array |

`extract` | Extract cell values from a SpatRaster (e.g., by cell, coordinates, polygon) |

`spatSample` | Regular or random sample |

`minmax` | Get the minimum and maximum value of the cells of a SpatRaster (if known) |

`setMinMax` | Compute the minimum and maximum value of a SpatRaster if these are not known |

`extract` | spatial queries of a SpatRaster with a SpatVector |

--------------------------- | ------------------------------------------------------------------------------------------ |

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

`ncol` | The number of columns |

`nrow` | The number of rows |

`ncell` | The number of cells (can not be set directly, only via ncol or nrow) |

`res` | The resolution (x and y) |

`nlyr` | Get or set the number of layers |

`names` | Get or set the layer names |

`xres` | The x resolution (can be set with res) |

`yres` | The y resolution (can be set with res) |

`xmin` | The minimum x coordinate (or longitude) |

`xmax` | The maximum x coordinate (or longitude) |

`ymin` | The minimum y coordinate (or latitude) |

`ymax` | The maximum y coordinate (or latitude) |

`ext` | Get or set the extent (minimum and maximum x and y coordinates ("bounding box") |

`origin` | The origin of a SpatRaster |

`crs` | The coordinate reference system (map projection) |

`is.lonlat` | Test if an object has (or may have) a longitude/latitude coordinate reference system |

`sources` | Get the filename(s) to which a SpatRaster is linked |

`inMemory` | Are the data sources in memory (or on disk)? |

`compareGeom` | Compare the geometry of SpatRasters |

`NAflag` | Set the `NA` value (for reading from a file with insufficient metadata) |

--------------------------- | ------------------------------------------------------------------------------------------ |

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.

`xFromCol` | x-coordinates from column numbers |

`yFromRow` | y-coordinates from row numbers |

`xFromCell` | x-coordinates from row numbers |

`yFromCell` | y-coordinates from cell numbers |

`xyFromCell` | x and y coordinates from cell numbers |

`colFromX` | Column numbers from x-coordinates (or longitude) |

`rowFromY` | Row numbers from y-coordinates (or latitude) |

`rowColFromCell` | Row and column numbers from cell numbers |

`cellFromXY` | Cell numbers from x and y coordinates |

`cellFromRowCol` | Cell numbers from row and column numbers |

`cellFromRowColCombine` | Cell numbers from all combinations of row and column numbers |

`cells` | Cell numbers from an SpatVector or SpatExtent |

--------------------------- | ------------------------------------------------------------------------------------------ |

`is.factor` | Are there categorical layers? |

`levels` | Get active categories, or set categories |

`activeCat` | Get or set the active category |

`cats` | Get categories (active and inactive) |

`set.cats` | Set categories in place |

`concats` | Combine SpatRasters with different categories |

`catalyze` | Create a layer for each category |

`as.numeric` | use the active category to create a non-categorical SpatRaster |

`as.factor` | Make the layers of a SpatRaster categorical |

--------------------------- | ------------------------------------------------------------------------------------------ |

`writeRaster` | Write all values of SpatRaster to disk. You can set the filetype, datatype, compression. |

`writeCDF` | Write SpatRaster data to a netCDF file |

--------------------------- | ------------------------------------------------------------------------------------------ |

`readStart` | Open file connections for efficient multi-chunk reading |

`readStop` | Close file connections |

`writeStart` | Open a file for writing |

`writeValues` | Write some values |

`writeStop` | Close the file after writing |

`blocks` | Get blocksize for reading files (when not writing) |

--------------------------- | ------------------------------------------------------------------------------------------ |

`terraOptions` | Show, set, or get session options, mostly to control memory use and to set write options |

`sources` | Show the data sources of a SpatRaster |

`tmpFiles` | Show or remove temporary files |

`mem_info` | memory needs and availability |

`inMemory` | Are the cell values in memory? |

--------------------------- | ------------------------------------------------------------------------------------------ |

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

`sds` | Create a SpatRasterDataset from a file with subdatasets (ncdf or hdf) or from SpatRaster objects |

`[` or `$` | Extract a SpatRaster |

`names` | Get the names of the sub-datasets |

--------------------------- | ------------------------------------------------------------------------------------------ |

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.

`sprc` | create a SpatRasterCollection from (a list of) SpatRaster objects |

`length` | how many SpatRasters does the SpatRasterCollection have? |

`crop` | crop a SpatRasterCollection |

`impose` | force the members of SpatRasterCollection to the same geometry |

`merge` | merge the members of a SpatRasterCollection |

`mosaic` | mosaic (merge with a function for overlapping areas) the members of a SpatRasterCollection |

`[` | extract a SpatRaster |

--------------------------- | ------------------------------------------------------------------------------------------ |

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

`vect` | Create a SpatVector from a file (for example a "shapefile") or from another object |

`vector_layers` | list or delete layers in a vector database such as GPGK |

`rbind` | append SpatVectors of the same geometry type |

`unique` | remove duplicates |

`na.omit` | remove empty geometries and/or fields that are `NA` |

`project` | Project a SpatVector to a different coordinate reference system |

`writeVector` | Write SpatVector data to disk |

`centroids` | Get the centroids of a SpatVector |

`voronoi` | Voronoi diagram |

`delaunay` | Delaunay triangles |

`convHull` | Compute the convex hull of a SpatVector |

`fillHoles` | Remove or extract holes from polygons |

--------------------------- | ------------------------------------------------------------------------------------------ |

`geom` | returns the geometries as matrix or WKT |

`crds` | returns the coordinates as a matrix |

`linearUnits` | returns the linear units of the crs (in meter) |

`ncol` | The number of columns (of the attributes) |

`nrow` | The number of rows (of the geometries and attributes) |

`names` | Get or set the layer names |

`ext` | Get the extent (minimum and maximum x and y coordinates ("bounding box") |

`crs` | The coordinate reference system (map projection) |

`is.lonlat` | Test if an object has (or may have) a longitude/latitude coordinate reference system |

--------------------------- | ------------------------------------------------------------------------------------------ |

`adjacent` | find adjacent polygons |

`expanse` | computes the area covered by polygons |

`nearby` | find nearby geometries |

`nearest` | find the nearest geometries |

`relate` | geometric relationships such as "intersects", "overlaps", and "touches" |

`perim` | computes the length of the perimeter of polygons, and the length of lines |

--------------------------- | ------------------------------------------------------------------------------------------ |

`erase` or "-" | erase (parts of) geometries |

`intersect` or "*" | intersect geometries |

`union` or "+" | Merge geometries |

`cover` | update polygons |

`symdif` | symmetrical difference of two polygons |

`aggregate` | dissolve smaller polygons into larger ones |

`buffer` | buffer geometries |

`disagg` | split multi-geometries into separate geometries |

`crop` | clip geometries using a rectangle (SpatExtent) or SpatVector |

--------------------------- | ------------------------------------------------------------------------------------------ |

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

`extract` | spatial queries between SpatVector and SpatVector (e.g. point in polygons) |

`sel` | select - interactively select geometries |

`click` | identify attributes by clicking on a map |

`merge` | Join a table with a SpatVector |

`as.data.frame` | get attributes as a data.frame |

`as.list` | get attributes as a list |

`values` | Get the attributes of a SpatVector |

`values<-` | Set new attributes to the geometries of a SpatRaster |

`sort` | sort SpatVector by the values in a field |

--------------------------- | ------------------------------------------------------------------------------------------ |

`shift` | change the position geometries by shifting their coordinates in horizontal and/or vertical direction |

`spin` | rotate geometries around an origin |

`rescale` | shrink (or expand) geometries, for example to make an inset map |

`flip` | flip geometries vertically or horizontally |

`t` | transpose geometries (switch x and y) |

--------------------------- | ------------------------------------------------------------------------------------------ |

`width` | the minimum diameter of the geometries |

`clearance` | the minimum clearance of the geometries |

`sharedPaths` | shared paths (arcs) between line or polygon geometries |

`simplifyGeom` | simplify geometries |

`gaps` | find gaps between polygon geometries |

`fillHoles` | get or remove the polygon holes |

`makeNodes` | create nodes on lines |

`mergeLines` | connect lines to form polygons |

`removeDupNodes` | remove duplicate nodes in geometries and optionally rounds the coordinates |

`is.valid` | check if geometries are valid |

`makeValid` | attempt to repair invalid geometries |

`snap` | make 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 |

`rotate` | rotate to (dis-) connect them across the date-line |

`normalize.longitude` | move geomtries that are outside of the -180 to 180 degrees range. |

`elongate` | make lines longer by extending both sides |

`combineGeoms` | combine geometries that overlap, share a border, or are within a minimum distance of each other |

--------------------------- | ------------------------------------------------------------------------------------------ |

A SpatVectorCollection is a vector of SpatVector objects.

`svc` | create a SpatVectorCollection from (a list of) SpatVector objects |

`length` | how many SpatRasters does the SpatRasterCollection have? |

`[` | extract a SpatVector |

--------------------------- | ------------------------------------------------------------------------------------------ |

`ext` | Create a SpatExtent object. For example to `crop` a Spatial dataset |

`intersect` | Intersect two SpatExtent objects, same as `-` |

`union` | Combine two SpatExtent objects, same as `+` |

`Math-methods` | round/floor/ceiling of a SpatExtent |

`align` | Align a SpatExtent with a SpatRaster |

`draw` | Create a SpatExtent by drawing it on top of a map (plot) |

--------------------------- | ------------------------------------------------------------------------------------------ |

`graticule` | Create a graticule |

`crop` | crop a graticule |

`plot<SpatGraticule>` | plot a graticule |

--------------------------- | ------------------------------------------------------------------------------------------ |

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)`

`rast` | SpatRaster from matrix and other objects |

`vect` | SpatVector from `sf` or `Spatial*` vector data |

`sf::st_as_sf` | sf object from SpatVector |

`rasterize` | Rasterizing points, lines or polygons |

`rasterizeWin` | Rasterize points with a moving window |

`rasterizeGeom` | Rasterize attributes of geometries such as "count", "area", or "length" |

`as.points` | Create points from a SpatRaster or SpatVector |

`as.lines` | Create points from a SpatRaster or SpatVector |

`as.polygons` | Create polygons from a SpatRaster |

`as.contour` | Contour lines from a SpatRaster |

--------------------------- | ------------------------------------------------------------------------------------------ |

`plot` | Plot a SpatRaster or SpatVector. The main method to create a map |

`panel` | Combine multiple plots |

`points` | Add points to a map |

`lines` | Add lines to a map |

`polys` | Add polygons to a map |

`text` | Add text (such as the values of a SpatRaster or SpatVector) to a map |

`halo` | Add text with a halo to a map |

`image` | Alternative to plot to make a map with a SpatRaster |

`plotRGB` | Combine three layers (red, green, blue channels) into a single "real color" plot |

`plot<SpatGraticule>` | plot a graticule |

`sbar` | Add a scale bar to a map |

`north` | Add a north arrow to a map |

`inset` | Add a small inset (overview) map |

`dots` | Make a dot-density map |

`cartogram` | Make a cartogram |

`persp` | Perspective plot of a SpatRaster |

`contour` | Contour plot or filled-contour plot of a SpatRaster |

`colorize` | Combine three layers (red, green, blue channels) into a single layer with a color-table |

--------------------------- | ------------------------------------------------------------------------------------------ |

`zoom` | Zoom in to a part of a map by drawing a bounding box on it |

`click` | Query values of SpatRaster or SpatVector by clicking on a map |

`sel` | Select a spatial subset of a SpatRaster or SpatVector by drawing on a map |

`draw` | Create a SpatExtent or SpatVector by drawing on a map |

--------------------------- | ------------------------------------------------------------------------------------------ |

`plot` | x-y scatter plot of the values of (a sample of) the layers of two SpatRaster objects |

`hist` | Histogram of SpatRaster values |

`barplot` | Bar plot of a SpatRaster |

`density` | Density plot of SpatRaster values |

`pairs` | Pairs plot for layers in a SpatRaster |

`boxplot` | Box plot of the values of a SpatRaster |

--------------------------- | ------------------------------------------------------------------------------------------ |

`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 package | terra package |

`raster, brick, stack` | `rast` |

`rasterFromXYZ` | `rast( , type="xyz")` |

`stack, addLayer` | `c` |

`addLayer` | `add<-` |

`area` | `cellSize` or `expanse` |

`approxNA` | `approximate` |

`calc` | `app` |

`cellFromLine, cellFromPolygon,` | `cells` |

`cellsFromExtent` | `cells` |

`cellStats` | `global` |

`clump` | `patches` |

`compareRaster` | `compareGeom` |

`corLocal` | `focalCor` |

`coordinates` | `crds` |

`couldBeLonLat` | `is.lonlat` |

`disaggregate` | `disagg` |

`distanceFromPoints` | `distance` |

`drawExtent, drawPoly, drawLine` | `draw` |

`dropLayer` | `subset` |

`extent` | `ext` |

`getValues` | `values` |

`isLonLat, isGlobalLonLat` | `is.lonlat` |

`layerize` | `segregate` |

`layerStats` | `layerCor` |

`movingFun` | `roll` |

`NAvalue` | `NAflag` |

`nlayers` | `nlyr` |

`overlay` | `lapp` |

`unstack` | `as.list` |

`projectRaster` | `project` |

`rasterToPoints` | `as.points` |

`rasterToPolygons` | `as.polygons` |

`reclassify, subs, cut` | `classify` |

`sampleRandom, sampleRegular` | `spatSample` |

`shapefile` | `vect` |

`stackApply` | `tapp` |

`stackSelect` | `selectRange` |

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). It other cases it simply seemed better. Here are some examples:

`as.polygons` | By default, `terra` returns dissolved polygons |

`quantile` | computes by cell, across layers instead of the other way around |

`extract` | By 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 | |

`values` | `terra` always returns a matrix. `raster` returns a vector for a `RasterLayer` |

`Summary-methods` | With `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) | |

--------------------------- | ------------------------------------------------------------------------------------------ |

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, Alex Ilich, Gerald Nelson, Jakub Nowosad and Monika Tomaszewska have been especially helpful.