Title: | Spatial Data Analysis |
---|---|
Description: | Methods for spatial data analysis with vector (points, lines, polygons) and raster (grid) data. Methods for vector data include geometric operations such as intersect and buffer. Raster methods include local, focal, global, zonal and geometric operations. The predict and interpolate methods facilitate the use of regression type (interpolation, machine learning) models for spatial prediction, including with satellite remote sensing data. Processing of very large files is supported. See the manual and tutorials on <https://rspatial.org/> to get started. 'terra' replaces the 'raster' package ('terra' can do more, and it is faster and easier to use). |
Authors: | Robert J. Hijmans [cre, aut] , Roger Bivand [ctb] , Emanuele Cordano [ctb] , Krzysztof Dyba [ctb] , Edzer Pebesma [ctb] , Michael D. Sumner [ctb] |
Maintainer: | Robert J. Hijmans <[email protected]> |
License: | GPL (>=3) |
Version: | 1.7-82 |
Built: | 2024-10-11 23:14:56 UTC |
Source: | https://github.com/rspatial/terra |
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.
———————————————————————————————————————
———————————————————————————————————————
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 |
regress |
Cell-based regression models |
--------------------------- | ------------------------------------------------------------------------------------------ |
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 coefficient) 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 viewshed (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 (regression or classification) model to a SpatRaster |
interpolate |
Predict a spatial model to a SpatRaster |
interpIDW |
Inverse-distance-weighted interpolation |
interpNear |
Nearest neighbor interpolation |
k_means |
k-means clustering of SpatRaster data |
princomp and prcomp |
Principal Component Analysis (PCA) with raster data |
--------------------------- | ------------------------------------------------------------------------------------------ |
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 (with cell numbers, coordinates, points, lines, or polygons) |
extractAlong |
Extract cell values along a line such that the values are in the right order |
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 (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 |
--------------------------- | ------------------------------------------------------------------------------------------ |
time |
Get or set time |
fillTime |
can add empty layers in between existing layers to assure that the time step between layers is constant |
mergeTime |
combine multiple rasters, perhaps partly overlapping in time, into a single time series |
--------------------------- | ------------------------------------------------------------------------------------------ |
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 SpatRasters that represent 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 SpatRasters |
[ 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) SpatRasters |
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 |
minRect |
Compute the minimum minimal bounding rotated rectangle of a SpatVector |
minCircle |
Compute the minimal bounding circle 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 geometries 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 |
forceCCW |
force counter-clockwise polygon winding |
--------------------------- | ------------------------------------------------------------------------------------------ |
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 lines 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 |
map.pal |
Color palettes for mapping |
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 |
add_legend |
Add a legend to a map |
add_box |
Add a bounding box to a map |
map_extent |
Get the coordinates of a map's axes positions |
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
|
focalPairs |
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). In 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) |
|
--------------------------- | ------------------------------------------------------------------------------------------ |
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.
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, Derek Friend, Alex Ilich, Gerald Nelson, Jakub Nowosad, and Monika Tomaszewska have been especially helpful.
Get or set the active category of a multi-categorical SpatRaster layer
## S4 method for signature 'SpatRaster' activeCat(x, layer=1) ## S4 replacement method for signature 'SpatRaster' activeCat(x, layer=1)<-value
## S4 method for signature 'SpatRaster' activeCat(x, layer=1) ## S4 replacement method for signature 'SpatRaster' activeCat(x, layer=1)<-value
x |
SpatRaster |
layer |
positive integer, the layer number or name |
value |
positive integer or character, indicating which column in the categories to use. Note that when a number is used this index is zero based, and "1" refers to the second column. This is because the first column of the categories has the cell values, not categorical labels |
integer
set.seed(0) r <- rast(nrows=10, ncols=10) values(r) <- sample(3, ncell(r), replace=TRUE) + 10 d <- data.frame(id=11:13, cover=c("forest", "water", "urban"), letters=letters[1:3], value=10:12) levels(r) <- d activeCat(r) activeCat(r) <- 3 activeCat(r)
set.seed(0) r <- rast(nrows=10, ncols=10) values(r) <- sample(3, ncell(r), replace=TRUE) + 10 d <- data.frame(id=11:13, cover=c("forest", "water", "urban"), letters=letters[1:3], value=10:12) levels(r) <- d activeCat(r) activeCat(r) <- 3 activeCat(r)
Add (in place) a SpatRaster to another SpatRaster. Comparable with c
, but without copying the object.
## S4 replacement method for signature 'SpatRaster,SpatRaster' add(x)<-value ## S4 replacement method for signature 'SpatRasterDataset,SpatRaster' add(x)<-value ## S4 replacement method for signature 'SpatRasterCollection,SpatRaster' add(x)<-value
## S4 replacement method for signature 'SpatRaster,SpatRaster' add(x)<-value ## S4 replacement method for signature 'SpatRasterDataset,SpatRaster' add(x)<-value ## S4 replacement method for signature 'SpatRasterCollection,SpatRaster' add(x)<-value
x |
SpatRaster, SpatRasterDataset or SpatRasterCollection |
value |
SpatRaster |
SpatRaster
r <- rast(nrows=5, ncols=9, vals=1:45) x <- c(r, r*2) add(x) <- r*3 x
r <- rast(nrows=5, ncols=9, vals=1:45) x <- c(r, r*2) add(x) <- r*3 x
Similar to box
allowing adding a box around a map. This function will place the box around the mapped area.
add_box(...)
add_box(...)
... |
arguments passed to |
add_legend
, add_grid
, add_mtext
v <- vect(system.file("ex/lux.shp", package="terra")) plot(v) add_box(col="red", lwd=3, xpd=TRUE)
v <- vect(system.file("ex/lux.shp", package="terra")) plot(v) add_box(col="red", lwd=3, xpd=TRUE)
Adaptation of grid
that allows adding a grid to a map. This function will place the legend in the locations within the mapped area as delineated by the axes.
Also see graticule
add_grid(nx=NULL, ny=nx, col="lightgray", lty="dotted", lwd=1)
add_grid(nx=NULL, ny=nx, col="lightgray", lty="dotted", lwd=1)
nx , ny
|
number of cells of the grid in x and y direction. When NULL, as per default, the grid aligns with the tick marks on the corresponding default axis (i.e., tickmarks as computed by axTicks). When NA, no grid lines are drawn in the corresponding direction |
col |
character or (integer) numeric; color of the grid lines |
lty |
character or (integer) numeric; line type of the grid lines |
lwd |
non-negative numeric giving line width of the grid lines |
graticule
, add_legend
, add_box
, add_grid
, add_mtext
v <- vect(system.file("ex/lux.shp", package="terra")) plot(v) add_grid()
v <- vect(system.file("ex/lux.shp", package="terra")) plot(v) add_grid()
Wrapper around legend
that allows adding a custom legend to a map using a keyword such as "topleft" or "bottomright". This function will place the legend in the locations within the mapped area as delineated by the axes.
add_legend(x, y, ...)
add_legend(x, y, ...)
x |
The keyword to be used to position the legend (or the x coordinate) |
y |
The y coordinate to be used to position the legend (is x is also a coordinate) |
... |
arguments passed to |
v <- vect(system.file("ex/lux.shp", package="terra")) plot(v) points(centroids(v), col="red") legend("topleft", legend = "centroids", pch = 20, xpd=NA, bg="white", col="red") add_legend("topright", legend = "centroids", pch = 20, col="red")
v <- vect(system.file("ex/lux.shp", package="terra")) plot(v) points(centroids(v), col="red") legend("topleft", legend = "centroids", pch = 20, xpd=NA, bg="white", col="red") add_legend("topright", legend = "centroids", pch = 20, col="red")
Similar to mtext
allowing adding a text to the margins of a map. This function useds the margins around the mapped area; not the margins that R would use.
add_mtext(text, side=3, line=0, ...)
add_mtext(text, side=3, line=0, ...)
text |
character or expression vector specifying the text to be written |
side |
integer indicating the margin to use (1=bottom, 2=left, 3=top, 4=right) |
line |
numeric to move the text in or outwards. |
... |
arguments passed to |
f <- system.file("ex/elev.tif", package="terra") r <- rast(f) plot(r, axes=FALSE, legend=FALSE) add_box() for (i in 1:4) add_mtext("margin text", i, cex=i, col=i, line=2-i)
f <- system.file("ex/elev.tif", package="terra") r <- rast(f) plot(r, axes=FALSE, legend=FALSE) add_box() for (i in 1:4) add_mtext("margin text", i, cex=i, col=i, line=2-i)
Identify cells that are adjacent to a set of raster cells. Or identify adjacent polygons
## S4 method for signature 'SpatRaster' adjacent(x, cells, directions="rook", pairs=FALSE, include=FALSE, symmetrical=FALSE) ## S4 method for signature 'SpatVector' adjacent(x, type="rook", pairs=TRUE, symmetrical=FALSE)
## S4 method for signature 'SpatRaster' adjacent(x, cells, directions="rook", pairs=FALSE, include=FALSE, symmetrical=FALSE) ## S4 method for signature 'SpatVector' adjacent(x, type="rook", pairs=TRUE, symmetrical=FALSE)
x |
SpatRaster |
cells |
vector of cell numbers for which adjacent cells should be found. Cell numbers start with 1 in the upper-left corner and increase from left to right and from top to bottom |
directions |
character or matrix to indicated the directions in which cells are considered connected. The following character values are allowed: "rook" or "4" for the horizontal and vertical neighbors; "bishop" to get the diagonal neighbors; "queen" or "8" to get the vertical, horizontal and diagonal neighbors; or "16" for knight and one-cell queen move neighbors. If |
pairs |
logical. If |
include |
logical. Should the focal cells be included in the result? |
type |
character. One of "rook", "queen", "touches", or "intersects". "queen" and "touches" are synonyms. "rook" exclude polygons that touch at a single node only. "intersects" includes polygons that touch or overlap |
symmetrical |
logical. If |
matrix
When using global lon/lat rasters, adjacent cells at the other side of the date-line are included.
r <- rast(nrows=10, ncols=10) adjacent(r, cells=c(1, 5, 55), directions="queen") r <- rast(nrows=10, ncols=10, crs="+proj=utm +zone=1 +datum=WGS84") adjacent(r, cells=11, directions="rook") #same as rk <- matrix(c(0,1,0,1,0,1,0,1,0), 3, 3) adjacent(r, cells=11, directions=rk) ## note that with global lat/lon data the E and W connect r <- rast(nrows=10, ncols=10, crs="+proj=longlat +datum=WGS84") adjacent(r, cells=11, directions="rook") f <- system.file("ex/lux.shp", package="terra") v <- vect(f) a <- adjacent(v, symmetrical=TRUE) head(a)
r <- rast(nrows=10, ncols=10) adjacent(r, cells=c(1, 5, 55), directions="queen") r <- rast(nrows=10, ncols=10, crs="+proj=utm +zone=1 +datum=WGS84") adjacent(r, cells=11, directions="rook") #same as rk <- matrix(c(0,1,0,1,0,1,0,1,0), 3, 3) adjacent(r, cells=11, directions=rk) ## note that with global lat/lon data the E and W connect r <- rast(nrows=10, ncols=10, crs="+proj=longlat +datum=WGS84") adjacent(r, cells=11, directions="rook") f <- system.file("ex/lux.shp", package="terra") v <- vect(f) a <- adjacent(v, symmetrical=TRUE) head(a)
Aggregate a SpatRaster to create a new SpatRaster with a lower resolution (larger cells). Aggregation groups rectangular areas to create larger cells. The value for the resulting cells is computed with a user-specified function.
You can also aggregate ("dissolve") a SpatVector. This either combines all geometries into one geometry, or it combines the geometries that have the same value for the variable(s) specified with argument by
.
## S4 method for signature 'SpatRaster' aggregate(x, fact=2, fun="mean", ..., cores=1, filename="", overwrite=FALSE, wopt=list()) ## S4 method for signature 'SpatVector' aggregate(x, by=NULL, dissolve=TRUE, fun="mean", count=TRUE, ...)
## S4 method for signature 'SpatRaster' aggregate(x, fact=2, fun="mean", ..., cores=1, filename="", overwrite=FALSE, wopt=list()) ## S4 method for signature 'SpatVector' aggregate(x, by=NULL, dissolve=TRUE, fun="mean", count=TRUE, ...)
x |
SpatRaster |
fact |
positive integer. Aggregation factor expressed as number of cells in each direction (horizontally and vertically). Or two integers (horizontal and vertical aggregation factor) or three integers (when also aggregating over layers) |
fun |
function used to aggregate values. Either an actual function, or for the following, their name: "mean", "max", "min", "median", "sum", "modal", "any", "all", "prod", "which.min", "which.max", "sd" (sample standard deviation) and "std" (population standard deviation) |
... |
additional arguments passed to |
cores |
positive integer. If |
filename |
character. Output filename |
overwrite |
logical. If |
wopt |
list with named options for writing files as in |
by |
character. The variable(s) used to group the geometries |
dissolve |
logical. Should borders between aggregated geometries be dissolved? |
count |
logical. If |
Aggregation starts at the upper-left end of a SpatRaster. If a division of the number of columns or rows with factor
does not return an integer, the extent of the resulting SpatRaster will be somewhat larger then that of the original SpatRaster. For example, if an input SpatRaster has 100 columns, and fact=12
, the output SpatRaster will have 9 columns and the maximum x coordinate of the output SpatRaster is also adjusted.
The function fun
should take multiple numbers, and return a single number. For example mean
, modal
, min
or max
.
It should also accept a na.rm
argument (or ignore it as one of the 'dots' arguments).
SpatRaster
disagg
to disaggregate
r <- rast() # aggregated SpatRaster, no values ra <- aggregate(r, fact=10) values(r) <- runif(ncell(r)) # aggregated raster, max of the values ra <- aggregate(r, fact=10, fun=max) # multiple layers s <- c(r, r*2) x <- aggregate(s, 20) ## SpatVector f <- system.file("ex/lux.shp", package="terra") v <- vect(f) va <- aggregate(v, "ID_1") plot(va, "NAME_1", lwd=5, plg=list(x="topright"), mar=rep(2,4)) lines(v, lwd=3, col="light gray") lines(va) text(v, "ID_1", halo=TRUE)
r <- rast() # aggregated SpatRaster, no values ra <- aggregate(r, fact=10) values(r) <- runif(ncell(r)) # aggregated raster, max of the values ra <- aggregate(r, fact=10, fun=max) # multiple layers s <- c(r, r*2) x <- aggregate(s, 20) ## SpatVector f <- system.file("ex/lux.shp", package="terra") v <- vect(f) va <- aggregate(v, "ID_1") plot(va, "NAME_1", lwd=5, plg=list(x="topright"), mar=rep(2,4)) lines(v, lwd=3, col="light gray") lines(va) text(v, "ID_1", halo=TRUE)
Align an SpatExtent with a SpatRaster This can be useful to create a new SpatRaster with the same origin and resolution as an existing SpatRaster. Do not use this to force data to match that really does not match (use e.g. resample
or (dis)aggregate for this).
It is also possible to align a SpatExtent to a clean divisor.
## S4 method for signature 'SpatExtent,SpatRaster' align(x, y, snap="near") ## S4 method for signature 'SpatExtent,numeric' align(x, y)
## S4 method for signature 'SpatExtent,SpatRaster' align(x, y, snap="near") ## S4 method for signature 'SpatExtent,numeric' align(x, y)
x |
SpatExtent |
y |
SpatRaster or numeric |
snap |
Character. One of "near", "in", or "out", to determine in which direction the extent should be aligned. To the nearest border, inwards or outwards |
SpatExtent
r <- rast() e <- ext(-10.1, 9.9, -20.1, 19.9) ea <- align(e, r) e ext(r) ea align(e, 0.5)
r <- rast() e <- ext(-10.1, 9.9, -20.1, 19.9) ea <- align(e, r) e ext(r) ea align(e, 0.5)
Compare two SpatRasters for (near) equality.
First the attributes of the objects are compared. If these are the same, a (perhaps small) sample of the raster cells is compared as well.
The sample size used can be increased with the maxcell
argument. You can set it to Inf
, but for large rasters your computer may not have sufficient memory. See the examples for a safe way to compare all values.
## S4 method for signature 'SpatRaster,SpatRaster' all.equal(target, current, maxcell=100000, ...)
## S4 method for signature 'SpatRaster,SpatRaster' all.equal(target, current, maxcell=100000, ...)
target |
SpatRaster |
current |
SpatRaster |
maxcell |
positive integer. The size of the regular sample used to compare cell values |
... |
additional arguments passed to |
Either TRUE
or a character vector describing the differences between target and current.
x <- sqrt(1:100) mat <- matrix(x, 10, 10) r1 <- rast(nrows=10, ncols=10, xmin=0, vals = x) r2 <- rast(nrows=10, ncols=10, xmin=0, vals = mat) all.equal(r1, r2) all.equal(r1, r1*1) all.equal(rast(r1), rast(r2)) # compare geometries compareGeom(r1, r2) # Compare all cell values for near equality # as floating point number imprecision can be a problem m <- minmax(r1 - r2) all(abs(m) < 1e-7) # comparison of cell values to create new SpatRaster e <- r1 == r2
x <- sqrt(1:100) mat <- matrix(x, 10, 10) r1 <- rast(nrows=10, ncols=10, xmin=0, vals = x) r2 <- rast(nrows=10, ncols=10, xmin=0, vals = mat) all.equal(r1, r2) all.equal(r1, r1*1) all.equal(rast(r1), rast(r2)) # compare geometries compareGeom(r1, r2) # Compare all cell values for near equality # as floating point number imprecision can be a problem m <- minmax(r1 - r2) all(abs(m) < 1e-7) # comparison of cell values to create new SpatRaster e <- r1 == r2
Animate (sequentially plot) the layers of a SpatRaster to create a movie.
This does not work with R-Studio.
## S4 method for signature 'SpatRaster' animate(x, pause=0.25, main, range, maxcell=50000, n=1, ...)
## S4 method for signature 'SpatRaster' animate(x, pause=0.25, main, range, maxcell=50000, n=1, ...)
x |
SpatRaster |
pause |
numeric. How long should be the pause be between layers? |
main |
title for each layer. If not supplied the z-value is used if available. Otherwise the names are used. |
range |
numeric vector of length 2. Range of values to plot |
maxcell |
positive integer. Maximum number of cells to use for the plot. If |
n |
integer > 0. Number of loops |
... |
Additional arguments passed to |
None
s <- rast(system.file("ex/logo.tif", package="terra")) animate(s, n=1)
s <- rast(system.file("ex/logo.tif", package="terra")) animate(s, n=1)
Apply a function to the values of each cell of a SpatRaster. Similar to apply
– think of each layer in a SpatRaster as a column (or row) in a matrix.
This is generally used to summarize the values of multiple layers into one layer; but this is not required.
app
calls function fun
with the raster data as first argument. Depending on the function supplied, the raster data is represented as either a matrix in which each layer is a column, or a vector representing a cell. The function should return a vector or matrix that is divisible by ncell(x). Thus, both "sum" and "rowSums" can be used, but "colSums" cannot be used.
You can also apply a function fun
across datasets by layer of a SpatRasterDataset
. In that case, summarization is by layer across SpatRasters.
## S4 method for signature 'SpatRaster' app(x, fun, ..., cores=1, filename="", overwrite=FALSE, wopt=list()) ## S4 method for signature 'SpatRasterDataset' app(x, fun, ..., cores=1, filename="", overwrite=FALSE, wopt=list())
## S4 method for signature 'SpatRaster' app(x, fun, ..., cores=1, filename="", overwrite=FALSE, wopt=list()) ## S4 method for signature 'SpatRasterDataset' app(x, fun, ..., cores=1, filename="", overwrite=FALSE, wopt=list())
x |
SpatRaster or SpatRasterDataset |
fun |
a function that operates on a vector or matrix. This can be a function that is defined in base-R or in a package, or a function you write yourself (see examples). Functions that return complex output (e.g. a list) may need to be wrapped in your own function to simplify the output to a vector or matrix. The following functions have been re-implemented in C++ for speed: "sum", "mean", "median", "modal", "which", "which.min", "which.max", "min", "max", "prod", "any", "all", "sd", "std", "first". To use the base-R function for say, "min", you could use something like |
... |
additional arguments for |
cores |
positive integer. If |
filename |
character. Output filename |
overwrite |
logical. If |
wopt |
list with named options for writing files as in |
To speed things up, parallelization is supported, but this is often not helpful, and it may actually be slower. There is only a speed gain if you have many cores (> 8) and/or a very complex (slow) function fun
. If you write fun
yourself, consider supplying a cppFunction
made with the Rcpp package instead (or go have a cup of tea while the computer works for you).
SpatRaster
lapp
, tapp
, Math-methods
, roll
r <- rast(ncols=10, nrows=10) values(r) <- 1:ncell(r) x <- c(r, sqrt(r), r+50) s <- app(x, fun=sum) s # for a few generic functions like # "sum", "mean", and "max" you can also do sum(x) ## SpatRasterDataset sd <- sds(x, x*2, x/3) a <- app(sd, max) a # same as max(x, x*2, x/3) # and as (but slower) b <- app(sd, function(i) max(i)) ## also works for a single layer f <- function(i) (i+1) * 2 * i + sqrt(i) s <- app(r, f) # same as above, but that is not memory-safe # and has no filename argument s <- f(r) ## Not run: #### multiple cores test0 <- app(x, sqrt) test1 <- app(x, sqrt, cores=2) testfun <- function(i) { 2 * sqrt(i) } test2 <- app(x, fun=testfun, cores =2) ## this fails because testfun is not exported to the nodes # test3 <- app(x, fun=function(i) testfun(i), cores=2) ## to export it, add it as argument to fun test3 <- app(x, fun=function(i, ff) ff(i), cores =3, ff=testfun) ## End(Not run)
r <- rast(ncols=10, nrows=10) values(r) <- 1:ncell(r) x <- c(r, sqrt(r), r+50) s <- app(x, fun=sum) s # for a few generic functions like # "sum", "mean", and "max" you can also do sum(x) ## SpatRasterDataset sd <- sds(x, x*2, x/3) a <- app(sd, max) a # same as max(x, x*2, x/3) # and as (but slower) b <- app(sd, function(i) max(i)) ## also works for a single layer f <- function(i) (i+1) * 2 * i + sqrt(i) s <- app(r, f) # same as above, but that is not memory-safe # and has no filename argument s <- f(r) ## Not run: #### multiple cores test0 <- app(x, sqrt) test1 <- app(x, sqrt, cores=2) testfun <- function(i) { 2 * sqrt(i) } test2 <- app(x, fun=testfun, cores =2) ## this fails because testfun is not exported to the nodes # test3 <- app(x, fun=function(i) testfun(i), cores=2) ## to export it, add it as argument to fun test3 <- app(x, fun=function(i, ff) ff(i), cores =3, ff=testfun) ## End(Not run)
NA
by interpolating between layersapproximate uses the stats
function approx
to estimate values for cells that are NA
by interpolation across layers. Layers are considered equidistant, unless argument z
is used, or time(x)
returns values that are not NA
, in which case these values are used to determine distance between layers.
For estimation based on neighboring cells see focal
## S4 method for signature 'SpatRaster' approximate(x, method="linear", yleft, yright, rule=1, f=0, ties=mean, z=NULL, NArule=1,filename="", ...)
## S4 method for signature 'SpatRaster' approximate(x, method="linear", yleft, yright, rule=1, f=0, ties=mean, z=NULL, NArule=1,filename="", ...)
x |
SpatRaster |
method |
specifies the interpolation method to be used. Choices are "linear" or "constant" (step function; see the example in |
yleft |
the value to be returned before a non- |
yright |
the value to be returned after the last non- |
rule |
an integer (of length 1 or 2) describing how interpolation is to take place at for the first and last cells (before or after any non- |
f |
for method = "constant" a number between 0 and 1 inclusive, indicating a compromise between left- and right-continuous step functions. If y0 and y1 are the values to the left and right of the point then the value is |
ties |
Handling of tied 'z' values. Either a function with a single vector argument returning a single number result or the string "ordered" |
z |
numeric vector to indicate the distance between layers (e.g., depth). The default is |
NArule |
single integer used to determine what to do when only a single layer with a non- |
filename |
character. Output filename |
... |
additional arguments for writing files as in |
SpatRaster
r <- rast(ncols=5, nrows=5) r1 <- setValues(r, runif(ncell(r))) r2 <- setValues(r, runif(ncell(r))) r3 <- setValues(r, runif(ncell(r))) r4 <- setValues(r, runif(ncell(r))) r5 <- setValues(r, NA) r6 <- setValues(r, runif(ncell(r))) r1[6:10] <- NA r2[5:15] <- NA r3[8:25] <- NA s <- c(r1,r2,r3,r4,r5,r6) s[1:5] <- NA x1 <- approximate(s) x2 <- approximate(s, rule=2) x3 <- approximate(s, rule=2, z=c(1,2,3,5,14,15))
r <- rast(ncols=5, nrows=5) r1 <- setValues(r, runif(ncell(r))) r2 <- setValues(r, runif(ncell(r))) r3 <- setValues(r, runif(ncell(r))) r4 <- setValues(r, runif(ncell(r))) r5 <- setValues(r, NA) r6 <- setValues(r, runif(ncell(r))) r1[6:10] <- NA r2[5:15] <- NA r3[8:25] <- NA s <- c(r1,r2,r3,r4,r5,r6) s[1:5] <- NA x1 <- approximate(s) x2 <- approximate(s, rule=2) x3 <- approximate(s, rule=2, z=c(1,2,3,5,14,15))
Standard arithmetic operators for computations with SpatRasters. Computations are local (applied on a cell by cell basis). If multiple SpatRasters are used, these must have the same geometry (extent and resolution). These operators have been implemented:
+, -, *, /, ^, %%, %/%
You can also use a SpatRaster and a vector or a matrix. If you use a SpatRaster with a vector of multiple numbers, each element in the vector is considered a layer (with a constant value). If you use a SpatRaster with a matrix, the number of columns of the matrix must match the number of layers of the SpatRaster. The rows are used to match the cells. That is, if there are two rows, these match cells 1 and 2, and they are recycled to 3 and 4, etc.
The following methods have been implemented for (SpatExtent, SpatExtent)
: +, -
, and the following for (SpatExtent, numeric)
: +, -, *, /, %%
SpatRaster or SpatExtent
ifel
to conveniently combine operations and Math-methods
or app
to use mathematical functions not implemented by the package.
r1 <- rast(ncols=10, nrows=10) v <- runif(ncell(r1)) v[10:20] <- NA values(r1) <- v r2 <- rast(r1) values(r2) <- 1:ncell(r2) / ncell(r2) r3 <- r1 + r2 r2 <- r1 / 10 r3 <- r1 * (r2 - 1 / r2) b <- c(r1, r2, r3) b2 <- b * 10 ### SpatExtent methods x <- ext(0.1, 2.2, 0, 3) y <- ext(-2, 1, -2,2) # union x + y # intersection x * y e <- x e e * 2 e / 2 e + 1 e - 1
r1 <- rast(ncols=10, nrows=10) v <- runif(ncell(r1)) v[10:20] <- NA values(r1) <- v r2 <- rast(r1) values(r2) <- 1:ncell(r2) / ncell(r2) r3 <- r1 + r2 r2 <- r1 / 10 r3 <- r1 * (r2 - 1 / r2) b <- c(r1, r2, r3) b2 <- b * 10 ### SpatExtent methods x <- ext(0.1, 2.2, 0, 3) y <- ext(-2, 1, -2,2) # union x + y # intersection x * y e <- x e e * 2 e / 2 e + 1 e - 1
Create a text representation of (the skeleton of) an object
## S4 method for signature 'SpatExtent' as.character(x) ## S4 method for signature 'SpatRaster' as.character(x)
## S4 method for signature 'SpatExtent' as.character(x) ## S4 method for signature 'SpatRaster' as.character(x)
x |
SpatRaster |
character
r <- rast() ext(r) ext(c(0, 20, 0, 20))
r <- rast() ext(r) ext(c(0, 20, 0, 20))
Coerce a SpatRaster or SpatVector to a data.frame
## S4 method for signature 'SpatVector' as.data.frame(x, row.names=NULL, optional=FALSE, geom=NULL, ...) ## S4 method for signature 'SpatRaster' as.data.frame(x, row.names=NULL, optional=FALSE, xy=FALSE, cells=FALSE, time=FALSE, na.rm=NA, wide=TRUE, ...)
## S4 method for signature 'SpatVector' as.data.frame(x, row.names=NULL, optional=FALSE, geom=NULL, ...) ## S4 method for signature 'SpatRaster' as.data.frame(x, row.names=NULL, optional=FALSE, xy=FALSE, cells=FALSE, time=FALSE, na.rm=NA, wide=TRUE, ...)
x |
SpatRaster or SpatVector |
geom |
character or NULL. If not NULL, either "WKT" or "HEX", to get the geometry included in Well-Known-Text or hexadecimal notation. If |
xy |
logical. If |
time |
logical. If |
na.rm |
logical. If |
cells |
logical. If |
wide |
logical. If |
... |
Additional arguments passed to the |
row.names |
This argument is ignored |
optional |
This argument is ignored |
data.frame
as.list, as.matrix
. See geom
to only extract the geometry of a SpatVector
f <- system.file("ex/lux.shp", package="terra") v <- vect(f) as.data.frame(v)
f <- system.file("ex/lux.shp", package="terra") v <- vect(f) as.data.frame(v)
Conversion of a SpatRaster, SpatVector or SpatExtent to a SpatVector of lines.
## S4 method for signature 'SpatRaster' as.lines(x) ## S4 method for signature 'SpatVector' as.lines(x) ## S4 method for signature 'SpatExtent' as.lines(x, crs="") ## S4 method for signature 'matrix' as.lines(x, crs="")
## S4 method for signature 'SpatRaster' as.lines(x) ## S4 method for signature 'SpatVector' as.lines(x) ## S4 method for signature 'SpatExtent' as.lines(x, crs="") ## S4 method for signature 'matrix' as.lines(x, crs="")
x |
SpatRaster, SpatVector, SpatExtent or matrix. If |
crs |
character. The coordinate reference system (see |
SpatVector
r <- rast(ncols=2, nrows=2) values(r) <- 1:ncell(r) as.lines(r) as.lines(ext(r), crs=crs(r)) if (gdal() >= "3.0.0") { p <- as.polygons(r) as.lines(p) } ## with a matrix s <- cbind(1:5, 1:5) e <- cbind(1:5, 0) as.lines(s) as.lines(cbind(s, e), "+proj=longlat")
r <- rast(ncols=2, nrows=2) values(r) <- 1:ncell(r) as.lines(r) as.lines(ext(r), crs=crs(r)) if (gdal() >= "3.0.0") { p <- as.polygons(r) as.lines(p) } ## with a matrix s <- cbind(1:5, 1:5) e <- cbind(1:5, 0) as.lines(s) as.lines(cbind(s, e), "+proj=longlat")
Coerce a SpatRaster, SpatRasterCollection, SpatRasterDataset, SpatVector or SpatVectorCollection to a list. With a SpatRaster, each layer becomes a list element. With a SpatRasterCollection or SpatRasterDataset, each SpatRaster becomes a list element. With a SpatVector, each variable (attribute) becomes a list element. With a SpatVectorCollection, each SpatVector becomes a list element.
## S4 method for signature 'SpatRaster' as.list(x, geom=NULL, ...) ## S4 method for signature 'SpatRasterCollection' as.list(x, ...) ## S4 method for signature 'SpatVector' as.list(x, geom=NULL, ...) ## S4 method for signature 'SpatVectorCollection' as.list(x, ...)
## S4 method for signature 'SpatRaster' as.list(x, geom=NULL, ...) ## S4 method for signature 'SpatRasterCollection' as.list(x, ...) ## S4 method for signature 'SpatVector' as.list(x, geom=NULL, ...) ## S4 method for signature 'SpatVectorCollection' as.list(x, ...)
x |
SpatRaster, SpatRasterDataset, SpatRasterCollection, or SpatVector |
geom |
character or NULL. If not NULL, and |
... |
additional arguments. These are ignored |
list
see coerce
for as.data.frame
with a SpatRaster; and geom
to only extract the geometry of a SpatVector
f <- system.file("ex/lux.shp", package="terra") v <- vect(f) as.list(v) s <- rast(system.file("ex/logo.tif", package="terra")) + 1 as.list(s)
f <- system.file("ex/lux.shp", package="terra") v <- vect(f) as.list(v) s <- rast(system.file("ex/logo.tif", package="terra")) + 1 as.list(s)
Conversion of a SpatRaster, SpatVector or SpatExtent to a SpatVector of points.
## S4 method for signature 'SpatRaster' as.points(x, values=TRUE, na.rm=TRUE, na.all=FALSE) ## S4 method for signature 'SpatVector' as.points(x, multi=FALSE, skiplast=TRUE) ## S4 method for signature 'SpatExtent' as.points(x, crs="")
## S4 method for signature 'SpatRaster' as.points(x, values=TRUE, na.rm=TRUE, na.all=FALSE) ## S4 method for signature 'SpatVector' as.points(x, multi=FALSE, skiplast=TRUE) ## S4 method for signature 'SpatExtent' as.points(x, crs="")
x |
SpatRaster, SpatVector or SpatExtent |
values |
logical; include cell values as attributes? |
multi |
logical. If |
skiplast |
logical. If |
na.rm |
logical. If |
na.all |
logical. If |
crs |
character. The coordinate reference system (see |
SpatVector
r <- rast(ncols=2, nrows=2) values(r) <- 1:ncell(r) as.points(r) if (gdal() >= "3.0.0") { p <- as.polygons(r) as.points(p) }
r <- rast(ncols=2, nrows=2) values(r) <- 1:ncell(r) as.points(r) if (gdal() >= "3.0.0") { p <- as.polygons(r) as.points(p) }
Conversion of a SpatRaster, SpatVector or SpatExtent to a SpatVector of polygons.
## S4 method for signature 'SpatRaster' as.polygons(x, round=TRUE, aggregate=TRUE, values=TRUE, na.rm=TRUE, na.all=FALSE, extent=FALSE, digits=0, ...) ## S4 method for signature 'SpatVector' as.polygons(x, extent=FALSE) ## S4 method for signature 'SpatExtent' as.polygons(x, crs="")
## S4 method for signature 'SpatRaster' as.polygons(x, round=TRUE, aggregate=TRUE, values=TRUE, na.rm=TRUE, na.all=FALSE, extent=FALSE, digits=0, ...) ## S4 method for signature 'SpatVector' as.polygons(x, extent=FALSE) ## S4 method for signature 'SpatExtent' as.polygons(x, crs="")
x |
SpatRaster, SpatVector or SpatExtent |
round |
logical; If |
aggregate |
logical; combine cells with the same values? If |
values |
logical; include cell values as attributes? |
extent |
logical. if |
na.rm |
logical. If |
na.all |
logical. If |
digits |
integer. The number of digits for rounding (if |
crs |
character. The coordinate reference system (see |
... |
additional arguments. For backward compatibility. Will be removed in the future |
SpatVector
r <- rast(ncols=2, nrows=2) values(r) <- 1:ncell(r) if (gdal() >= "3.0.0") { p <- as.polygons(r) p }
r <- rast(ncols=2, nrows=2) values(r) <- 1:ncell(r) if (gdal() >= "3.0.0") { p <- as.polygons(r) p }
Implementation of the generic as.raster
function to create a "raster" (small r) object. Such objects can be used for plotting with the rasterImage
function. NOT TO BE CONFUSED with the Raster* (big R) objects defined by the 'raster' package!
## S4 method for signature 'SpatRaster' as.raster(x, maxcell=500000, col)
## S4 method for signature 'SpatRaster' as.raster(x, maxcell=500000, col)
x |
SpatRaster |
maxcell |
positive integer. Maximum number of cells to use for the plot |
col |
vector of colors. The default is |
'raster' object
r <- rast(ncols=3, nrows=3) values(r) <- 1:ncell(r) as.raster(r)
r <- rast(ncols=3, nrows=3) values(r) <- 1:ncell(r) as.raster(r)
For SpatRasters x and y, atan2(y, x) returns the angle in radians for the tangent y/x, handling the case when x is zero. See Trig
See Math-methods
for other trigonometric and mathematical functions that can be used with SpatRasters.
## S4 method for signature 'SpatRaster,SpatRaster' atan2(y, x) ## S4 method for signature 'SpatRaster,SpatRaster' atan_2(y, x, filename, ...)
## S4 method for signature 'SpatRaster,SpatRaster' atan2(y, x) ## S4 method for signature 'SpatRaster,SpatRaster' atan_2(y, x, filename, ...)
y |
SpatRaster |
x |
SpatRaster |
filename |
character. Output filename |
... |
additional arguments for writing files as in |
r1 <- rast(nrows=10, ncols=10) r2 <- rast(nrows=10, ncols=10) values(r1) <- (runif(ncell(r1))-0.5) * 10 values(r2) <- (runif(ncell(r1))-0.5) * 10 atan2(r1, r2)
r1 <- rast(nrows=10, ncols=10) r2 <- rast(nrows=10, ncols=10) values(r1) <- (runif(ncell(r1))-0.5) * 10 values(r2) <- (runif(ncell(r1))-0.5) * 10 atan2(r1, r2)
Compute spatial autocorrelation for a numeric vector or a SpatRaster. You can compute standard (global) Moran's I or Geary's C, or local indicators of spatial autocorrelation (Anselin, 1995).
## S4 method for signature 'numeric' autocor(x, w, method="moran") ## S4 method for signature 'SpatRaster' autocor(x, w=matrix(c(1,1,1,1,0,1,1,1,1),3), method="moran", global=TRUE)
## S4 method for signature 'numeric' autocor(x, w, method="moran") ## S4 method for signature 'SpatRaster' autocor(x, w=matrix(c(1,1,1,1,0,1,1,1,1),3), method="moran", global=TRUE)
x |
numeric or SpatRaster |
w |
Spatial weights defined by or a rectangular matrix. For a SpatRaster this matrix must the sides must have an odd length (3, 5, ...) |
global |
logical. If |
method |
character. If |
The default setting uses a 3x3 neighborhood to compute "Queen's case" indices. You can use a filter (weights matrix) to do other things, such as "Rook's case", or different lags.
numeric or SpatRaster
Moran, P.A.P., 1950. Notes on continuous stochastic phenomena. Biometrika 37:17-23
Geary, R.C., 1954. The contiguity ratio and statistical mapping. The Incorporated Statistician 5: 115-145
Anselin, L., 1995. Local indicators of spatial association-LISA. Geographical Analysis 27:93-115
https://en.wikipedia.org/wiki/Indicators_of_spatial_association
The spdep
package for additional and more general approaches for computing spatial autocorrelation
### raster r <- rast(nrows=10, ncols=10, xmin=0) values(r) <- 1:ncell(r) autocor(r) # rook's case neighbors f <- matrix(c(0,1,0,1,0,1,0,1,0), nrow=3) autocor(r, f) # local rc <- autocor(r, w=f, global=FALSE) ### numeric (for vector data) f <- system.file("ex/lux.shp", package="terra") v <- vect(f) w <- relate(v, relation="touches") # global autocor(v$AREA, w) # local v$Gi <- autocor(v$AREA, w, "Gi") plot(v, "Gi")
### raster r <- rast(nrows=10, ncols=10, xmin=0) values(r) <- 1:ncell(r) autocor(r) # rook's case neighbors f <- matrix(c(0,1,0,1,0,1,0,1,0), nrow=3) autocor(r, f) # local rc <- autocor(r, w=f, global=FALSE) ### numeric (for vector data) f <- system.file("ex/lux.shp", package="terra") v <- vect(f) w <- relate(v, relation="touches") # global autocor(v$AREA, w) # local v$Gi <- autocor(v$AREA, w, "Gi") plot(v, "Gi")
Create a barplot of the values of the first layer of a SpatRaster. For large datasets a regular sample with a size of approximately maxcells
is used.
## S4 method for signature 'SpatRaster' barplot(height, maxcell=1000000, digits=0, breaks=NULL, col, ...)
## S4 method for signature 'SpatRaster' barplot(height, maxcell=1000000, digits=0, breaks=NULL, col, ...)
height |
SpatRaster |
maxcell |
integer. To regularly subsample very large datasets |
digits |
integer used to determine how to |
breaks |
breaks used to group the data as in |
col |
a color generating function such as |
... |
additional arguments for plotting as in |
A numeric vector (or matrix, when beside = TRUE
) of the coordinates of the bar midpoints, useful for adding to the graph. See barplot
f <- system.file("ex/elev.tif", package="terra") r <- rast(f) barplot(r, digits=-1, las=2, ylab="Frequency") op <- par(no.readonly = TRUE) par(mai = c(1, 2, .5, .5)) barplot(r, breaks=10, col=c("red", "blue"), horiz=TRUE, digits=NULL, las=1) par(op)
f <- system.file("ex/elev.tif", package="terra") r <- rast(f) barplot(r, digits=-1, las=2, ylab="Frequency") op <- par(no.readonly = TRUE) par(mai = c(1, 2, .5, .5)) barplot(r, breaks=10, col=c("red", "blue"), horiz=TRUE, digits=NULL, las=1) par(op)
Determine for each grid cell which reference it is most similar to. A reference consists of a SpatVector with reference locations, or a data.frame in which each column matches a layer name in the SpatRaster.
Similarity is computed with the sum of squared differences between the cell and the reference. It may be important to first scale the input.
## S4 method for signature 'SpatRaster,SpatVector' bestMatch(x, y, labels="", filename="", ...) ## S4 method for signature 'SpatRaster,data.frame' bestMatch(x, y, labels="", filename="", ...)
## S4 method for signature 'SpatRaster,SpatVector' bestMatch(x, y, labels="", filename="", ...) ## S4 method for signature 'SpatRaster,data.frame' bestMatch(x, y, labels="", filename="", ...)
x |
SpatRaster |
y |
SpatVector or data.frame |
labels |
character. labels that correspond to each class (row in |
filename |
character. Output filename |
... |
additional arguments for writing files as in |
SpatRaster
f <- system.file("ex/logo.tif", package = "terra") r <- rast(f) # locations of interest pts <- vect(cbind(c(25.25, 34.324, 43.003), c(54.577, 46.489, 30.905))) pts$code <- LETTERS[1:3] plot(r) points(pts, pch=20, cex=2, col="red") text(pts, "code", pos=4, halo=TRUE) x <- scale(r) s1 <- bestMatch(x, pts, labels=pts$code) plot(s1) # same result e <- extract(x, pts, ID=FALSE) s2 <- bestMatch(x, e, labels=c("Ap", "Nt", "Ms"))
f <- system.file("ex/logo.tif", package = "terra") r <- rast(f) # locations of interest pts <- vect(cbind(c(25.25, 34.324, 43.003), c(54.577, 46.489, 30.905))) pts$code <- LETTERS[1:3] plot(r) points(pts, pch=20, cex=2, col="red") text(pts, "code", pos=4, halo=TRUE) x <- scale(r) s1 <- bestMatch(x, pts, labels=pts$code) plot(s1) # same result e <- extract(x, pts, ID=FALSE) s2 <- bestMatch(x, e, labels=c("Ap", "Nt", "Ms"))
Detect boundaries (edges). Boundaries are cells that have more than one class in the 4 or 8 cells surrounding it, or, if classes=FALSE
, cells with values and cells with NA
.
## S4 method for signature 'SpatRaster' boundaries(x, classes=FALSE, inner=TRUE, directions=8, falseval=0, filename="", ...)
## S4 method for signature 'SpatRaster' boundaries(x, classes=FALSE, inner=TRUE, directions=8, falseval=0, filename="", ...)
x |
SpatRaster |
inner |
logical. If |
classes |
character. Logical. If |
directions |
integer. Which cells are considered adjacent? Should be 8 (Queen's case) or 4 (Rook's case) |
falseval |
numeric. The value to use for cells that are not a boundary and not |
filename |
character. Output filename |
... |
options for writing files as in |
SpatRaster. Cell values are either 1 (a border) or 0 (not a border), or NA
r <- rast(nrows=18, ncols=36, xmin=0) r[150:250] <- 1 r[251:450] <- 2 bi <- boundaries(r) bo <- boundaries(r, inner=FALSE) bc <- boundaries(r, classes=TRUE) #plot(bc)
r <- rast(nrows=18, ncols=36, xmin=0) r[150:250] <- 1 r[251:450] <- 2 bi <- boundaries(r) bo <- boundaries(r, inner=FALSE) bc <- boundaries(r, classes=TRUE) #plot(bc)
Box plot of layers in a SpatRaster
## S4 method for signature 'SpatRaster' boxplot(x, y=NULL, maxcell=100000, ...)
## S4 method for signature 'SpatRaster' boxplot(x, y=NULL, maxcell=100000, ...)
x |
SpatRaster |
y |
NULL or a SpatRaster. If |
maxcell |
Integer. Number of cells to sample from datasets |
... |
additional arguments passed to |
boxplot returns a list (invisibly) that can be used with bxp
r1 <- r2 <- r3 <- rast(ncols=10, nrows=10) set.seed(409) values(r1) <- rnorm(ncell(r1), 100, 40) values(r2) <- rnorm(ncell(r1), 80, 10) values(r3) <- rnorm(ncell(r1), 120, 30) s <- c(r1, r2, r3) names(s) <- c("Apple", "Pear", "Cherry") boxplot(s, notch=TRUE, col=c("red", "blue", "orange"), main="Box plot", ylab="random", las=1) op <- par(no.readonly = TRUE) par(mar=c(4,6,2,2)) boxplot(s, horizontal=TRUE, col="lightskyblue", axes=FALSE) axis(1) axis(2, at=0:3, labels=c("", names(s)), las=1, cex.axis=.9, lty=0) par(op) ## boxplot with 2 layers v <- vect(system.file("ex/lux.shp", package="terra")) r <- rast(system.file("ex/elev.tif", package="terra")) y <- rasterize(v, r, "NAME_2") b <- boxplot(r, y) bxp(b)
r1 <- r2 <- r3 <- rast(ncols=10, nrows=10) set.seed(409) values(r1) <- rnorm(ncell(r1), 100, 40) values(r2) <- rnorm(ncell(r1), 80, 10) values(r3) <- rnorm(ncell(r1), 120, 30) s <- c(r1, r2, r3) names(s) <- c("Apple", "Pear", "Cherry") boxplot(s, notch=TRUE, col=c("red", "blue", "orange"), main="Box plot", ylab="random", las=1) op <- par(no.readonly = TRUE) par(mar=c(4,6,2,2)) boxplot(s, horizontal=TRUE, col="lightskyblue", axes=FALSE) axis(1) axis(2, at=0:3, labels=c("", names(s)), las=1, cex.axis=.9, lty=0) par(op) ## boxplot with 2 layers v <- vect(system.file("ex/lux.shp", package="terra")) r <- rast(system.file("ex/elev.tif", package="terra")) y <- rasterize(v, r, "NAME_2") b <- boxplot(r, y) bxp(b)
Calculate a buffer around all cells that are not NA
in a SpatRaster, or around the geometries of a SpatVector.
SpatRaster cells inside the buffer distance get a value of 1.
Note that the distance unit of the buffer width
parameter is meters if the CRS is (+proj=longlat
), and in map units (typically also meters) if not.
## S4 method for signature 'SpatRaster' buffer(x, width, background=0, filename="", ...) ## S4 method for signature 'SpatVector' buffer(x, width, quadsegs=10, capstyle="round", joinstyle="round", mitrelimit=NA, singlesided=FALSE)
## S4 method for signature 'SpatRaster' buffer(x, width, background=0, filename="", ...) ## S4 method for signature 'SpatVector' buffer(x, width, quadsegs=10, capstyle="round", joinstyle="round", mitrelimit=NA, singlesided=FALSE)
x |
SpatRaster or SpatVector |
width |
numeric. Unit is meter if |
filename |
character. Output filename |
... |
additional arguments for writing files as in |
background |
numeric. value to assign to cells outside the buffer. If this value is zero or FALSE, a boolean SpatRaster is returned |
quadsegs |
positive integer. Number of line segments to use to draw a quart circle |
capstyle |
character. One of "round", "square" or "flat". Ignored if |
joinstyle |
character. One of "round", "mitre" or "bevel". Ignored if |
mitrelimit |
numeric. Place an upper bound on a mitre join to avoid it from extending very far from acute angles in the input geometry. Ignored if |
singlesided |
logical. If |
Same as x
r <- rast(ncols=36, nrows=18) r[500] <- 1 b <- buffer(r, width=5000000) plot(b) v <- vect(rbind(c(10,10), c(0,60)), crs="+proj=merc") b <- buffer(v, 20) plot(b) points(v) crs(v) <- "+proj=longlat" b <- buffer(v, 1500000) plot(b) points(v)
r <- rast(ncols=36, nrows=18) r[500] <- 1 b <- buffer(r, width=5000000) plot(b) v <- vect(rbind(c(10,10), c(0,60)), crs="+proj=merc") b <- buffer(v, 20) plot(b) points(v) crs(v) <- "+proj=longlat" b <- buffer(v, 1500000) plot(b) points(v)
With c
you can:
– Combine SpatRaster
objects. They must have the same extent and resolution. However, if x
is empty (has no cell values), its geometry is ignored with a warning. Two empty SpatRasters with the same geometry can also be combined (to get a summed number of layers). Also see add<-
– Add a SpatRaster
to a SpatRasterDataset
or SpatRasterCollection
– Add SpatVector
objects to a new or existing SpatVectorCollection
To append SpatVectors, use rbind
.
## S4 method for signature 'SpatRaster' c(x, ..., warn=TRUE) ## S4 method for signature 'SpatRasterDataset' c(x, ...) ## S4 method for signature 'SpatRasterCollection' c(x, ...) ## S4 method for signature 'SpatVector' c(x, ...) ## S4 method for signature 'SpatVectorCollection' c(x, ...)
## S4 method for signature 'SpatRaster' c(x, ..., warn=TRUE) ## S4 method for signature 'SpatRasterDataset' c(x, ...) ## S4 method for signature 'SpatRasterCollection' c(x, ...) ## S4 method for signature 'SpatVector' c(x, ...) ## S4 method for signature 'SpatVectorCollection' c(x, ...)
x |
SpatRaster, SpatVector, SpatRasterDataset or SpatVectorCollection |
warn |
logical. If |
... |
as for |
Same class as x
r <- rast(nrows=5, ncols=9) values(r) <- 1:ncell(r) x <- c(r, r*2, r*3)
r <- rast(nrows=5, ncols=9) values(r) <- 1:ncell(r) x <- c(r, r*2, r*3)
Make a cartogram, that is, a map where the area of polygons is made proportional to another variable. This can be a good way to map raw count data (e.g. votes).
## S4 method for signature 'SpatVector' cartogram(x, var, type)
## S4 method for signature 'SpatVector' cartogram(x, var, type)
x |
SpatVector |
var |
character. A variable name in |
type |
character. Cartogram type, only "nc" (non-contiguous) is currently supported |
SpatVector
f <- system.file("ex/lux.shp", package="terra") v <- vect(f) v$value <- 1:12 p <- cartogram(v, "value", "nc") plot(v, col="light gray", border="gray") lines(p, col="red", lwd=2)
f <- system.file("ex/lux.shp", package="terra") v <- vect(f) v$value <- 1:12 p <- cartogram(v, "value", "nc") plot(v, col="light gray", border="gray") lines(p, col="red", lwd=2)
Change a categorical layer into one or more numerical layers. With as.numeric
you can transfer the active category values to cell values in a non-categorical SpatRaster. catalyze
creates new layers for each category.
## S4 method for signature 'SpatRaster' as.numeric(x, index=NULL, filename="", ...) ## S4 method for signature 'SpatRaster' catalyze(x, filename="", ...)
## S4 method for signature 'SpatRaster' as.numeric(x, index=NULL, filename="", ...) ## S4 method for signature 'SpatRaster' catalyze(x, filename="", ...)
x |
SpatRaster |
index |
positive integer or category indicating the category to use. If |
filename |
character. Output filename |
... |
additional arguments for writing files as in |
SpatRaster
set.seed(0) r <- rast(nrows=10, ncols=10) values(r) <- sample(3, ncell(r), replace=TRUE) + 10 d <- data.frame(id=11:13, cover=c("forest", "water", "urban"), letters=letters[1:3], value=10:12) levels(r) <- d catalyze(r) activeCat(r) <- 3 as.numeric(r)
set.seed(0) r <- rast(nrows=10, ncols=10) values(r) <- sample(3, ncell(r), replace=TRUE) + 10 d <- data.frame(id=11:13, cover=c("forest", "water", "urban"), letters=letters[1:3], value=10:12) levels(r) <- d catalyze(r) activeCat(r) <- 3 as.numeric(r)
Get the cell numbers covered by a SpatVector or SpatExtent. Or that match values in a vector; or all non NA
values.
## S4 method for signature 'SpatRaster,missing' cells(x, y) ## S4 method for signature 'SpatRaster,numeric' cells(x, y, pairs=FALSE) ## S4 method for signature 'SpatRaster,SpatVector' cells(x, y, method="simple", weights=FALSE, exact=FALSE, touches=is.lines(y), small=TRUE) ## S4 method for signature 'SpatRaster,SpatExtent' cells(x, y)
## S4 method for signature 'SpatRaster,missing' cells(x, y) ## S4 method for signature 'SpatRaster,numeric' cells(x, y, pairs=FALSE) ## S4 method for signature 'SpatRaster,SpatVector' cells(x, y, method="simple", weights=FALSE, exact=FALSE, touches=is.lines(y), small=TRUE) ## S4 method for signature 'SpatRaster,SpatExtent' cells(x, y)
x |
SpatRaster |
y |
SpatVector, SpatExtent, 2-column matrix representing points, numeric representing values to match, or missing |
method |
character. Method for getting cell numbers for points. The default is "simple", the alternative is "bilinear". If it is "bilinear", the four nearest cells and their weights are returned |
weights |
logical. If |
pairs |
logical. If |
exact |
logical. If |
touches |
logical. If |
small |
logical. If |
numeric vector or matrix
r <- rast(ncols=10, nrows=10) values(r) <- 1:ncell(r) r[c(1:25, 31:100)] <- NA r <- ifel(r > 28, r + 10, r) # all cell numbers of cells that are not NA cells(r) # cell numbers that match values x <- cells(r, c(28,38)) x$lyr.1 # cells for points m <- cbind(x=c(0,10,-30), y=c(40,-10,20)) cellFromXY(r, m) v <- vect(m) cells(r, v) cells(r, v, method="bilinear") # cells for polygons f <- system.file("ex/lux.shp", package="terra") v <- vect(f) r <- rast(v) cv <- cells(r, v)
r <- rast(ncols=10, nrows=10) values(r) <- 1:ncell(r) r[c(1:25, 31:100)] <- NA r <- ifel(r > 28, r + 10, r) # all cell numbers of cells that are not NA cells(r) # cell numbers that match values x <- cells(r, c(28,38)) x$lyr.1 # cells for points m <- cbind(x=c(0,10,-30), y=c(40,-10,20)) cellFromXY(r, m) v <- vect(m) cells(r, v) cells(r, v, method="bilinear") # cells for polygons f <- system.file("ex/lux.shp", package="terra") v <- vect(f) r <- rast(v) cv <- cells(r, v)
Compute the area covered by individual raster cells.
Computing the surface area of raster cells is especially relevant for longitude/latitude rasters.
But note that for both angular (longitude/latitude) and for planar (projected) coordinate reference systems raster cells sizes are generally not constant, unless you are using an equal-area coordinate reference system.
For planar CRSs, the area is therefore not computed based on the linear units of the coordinate reference system, but on the *actual* area by transforming cells to longitude/latitude. If you do not want that correction, you can use transform=FALSE
or init(x, prod(res(x)))
## S4 method for signature 'SpatRaster' cellSize(x, mask=FALSE, lyrs=FALSE, unit="m", transform=TRUE, rcx=100, filename="", ...)
## S4 method for signature 'SpatRaster' cellSize(x, mask=FALSE, lyrs=FALSE, unit="m", transform=TRUE, rcx=100, filename="", ...)
x |
SpatRaster |
mask |
logical. If |
lyrs |
logical. If |
unit |
character. One of "m", "km", or "ha" |
transform |
logical. If |
rcx |
positive integer. The maximum number of rows and columns to be used to compute area of planar data if |
filename |
character. Output filename |
... |
additional arguments for writing files as in |
SpatRaster
# SpatRaster r <- rast(nrows=18, ncols=36) v <- 1:ncell(r) v[200:400] <- NA values(r) <- v # size of each raster cell a <- cellSize(r) # illustration of distortion r <- rast(ncols=90, nrows=45, ymin=-80, ymax=80) m <- project(r, "+proj=merc") bad <- init(m, prod(res(m)) / 1000000, names="naive") good <- cellSize(m, unit="km", names="corrected") plot(c(good, bad), nc=1, mar=c(2,2,1,6))
# SpatRaster r <- rast(nrows=18, ncols=36) v <- 1:ncell(r) v[200:400] <- NA values(r) <- v # size of each raster cell a <- cellSize(r) # illustration of distortion r <- rast(ncols=90, nrows=45, ymin=-80, ymax=80) m <- project(r, "+proj=merc") bad <- init(m, prod(res(m)) / 1000000, names="naive") good <- cellSize(m, unit="km", names="corrected") plot(c(good, bad), nc=1, mar=c(2,2,1,6))
Get the centroids of polygons or lines, or centroid-like points that are guaranteed to be inside the polygons or on the lines.
## S4 method for signature 'SpatVector' centroids(x, inside=FALSE)
## S4 method for signature 'SpatVector' centroids(x, inside=FALSE)
x |
SpatVector |
inside |
logical. If |
SpatVector of points
f <- system.file("ex/lux.shp", package="terra") v <- vect(f) x <- centroids(v) y <- centroids(v, TRUE)
f <- system.file("ex/lux.shp", package="terra") v <- vect(f) x <- centroids(v) y <- centroids(v, TRUE)
Clamp values to a minimum and maximum value. That is, all values below a lower threshold value and above the upper threshold value become either NA
, or, if values=TRUE
, become the threshold value
## S4 method for signature 'SpatRaster' clamp(x, lower=-Inf, upper=Inf, values=TRUE, filename="", ...) ## S4 method for signature 'numeric' clamp(x, lower=-Inf, upper=Inf, values=TRUE, ...)
## S4 method for signature 'SpatRaster' clamp(x, lower=-Inf, upper=Inf, values=TRUE, filename="", ...) ## S4 method for signature 'numeric' clamp(x, lower=-Inf, upper=Inf, values=TRUE, ...)
x |
SpatRaster |
lower |
numeric with the lowest acceptable value (you can specify a different value for each layer). Or a SpatRaster that has a single layer or the same number of layers as |
upper |
numeric with the highest acceptable value (you can specify a different value for each layer). Or a SpatRaster that has a single layer or the same number of layers as |
values |
logical. If |
filename |
character. Output filename |
... |
additional arguments for writing files as in |
SpatRaster
r <- rast(ncols=10, nrows=10) values(r) <- 1:ncell(r) rc <- clamp(r, 25, 75) rc
r <- rast(ncols=10, nrows=10) values(r) <- 1:ncell(r) rc <- clamp(r, 25, 75) rc
clamp time-series datat that are S shaped. The value in layers before the minimum value in a cell can be set to that minimum value, and the value in layers after the maximum value for a cell can be set to that maximum value.
## S4 method for signature 'SpatRaster' clamp_ts(x, min=FALSE, max=TRUE, filename="", ...)
## S4 method for signature 'SpatRaster' clamp_ts(x, min=FALSE, max=TRUE, filename="", ...)
x |
SpatRaster |
min |
logical. If |
max |
logical. If |
filename |
character. Output filename |
... |
additional arguments for writing files as in |
SpatRaster
sigm <- function(x) { .8 / (1 + exp(-(x-10))) + runif(length(x))/4 } r <- rast(ncols=10, nrows=10, nlyr=50) s <- seq(5.2, 15,.2) set.seed(1) values(r) <- t(replicate(100, sigm(s))) x <- clamp_ts(r, TRUE, TRUE) plot(unlist(r[4])) lines(unlist(x[4]))
sigm <- function(x) { .8 / (1 + exp(-(x-10))) + runif(length(x))/4 } r <- rast(ncols=10, nrows=10, nlyr=50) s <- seq(5.2, 15,.2) set.seed(1) values(r) <- t(replicate(100, sigm(s))) x <- clamp_ts(r, TRUE, TRUE) plot(unlist(r[4])) lines(unlist(x[4]))
Classify values of a SpatRaster. The function (re-)classifies groups of values to other values.
The classification is done based on the argument rcl
. You can classify ranges by specifying a three-column matrix "from-to-becomes" or change specific values by using a two-column matrix "is-becomes". You can also supply a vector with "cuts" or the "number of cuts".
With "from-to-becomes" or "is-becomes" classification is done in the row order of the matrix. Thus, if there are overlapping ranges or values, the first time a number is within a range determines the reclassification value.
With "cuts" the values are sorted, so that the order in which they are provided does not matter.
## S4 method for signature 'SpatRaster' classify(x, rcl, include.lowest=FALSE, right=TRUE, others=NULL, brackets=TRUE, filename="", ...)
## S4 method for signature 'SpatRaster' classify(x, rcl, include.lowest=FALSE, right=TRUE, others=NULL, brackets=TRUE, filename="", ...)
x |
SpatRaster |
rcl |
matrix for classification. This matrix must have 1, 2 or 3 columns. If there are three columns, the first two columns are "from" "to" of the input values, and the third column "becomes" has the new value for that range. The two column matrix ("is", "becomes") can be useful for classifying integer values. In that case, the arguments A single column matrix (or a vector) is interpreted as a set of cuts if there is more than one value. In that case the values are classified based on their location in-between the cut-values. If a single number is provided, that is used to make that number of cuts, at equal intervals between the lowest and highest values of the SpatRaster. |
include.lowest |
logical, indicating if a value equal to the lowest value in |
right |
logical. If |
others |
numeric. If not |
brackets |
logical. If |
filename |
character. Output filename |
... |
Additional arguments for writing files as in |
SpatRaster
classify works with the "raw" values of categorical rasters, ignoring the levels (labels, categories). To change the labels of categorical rasters, use subst
instead.
For model-based classification see predict
subst
for simpler from-to replacement
r <- rast(ncols=10, nrows=10) values(r) <- (0:99)/99 ## from-to-becomes # classify the values into three groups # all values >= 0 and <= 0.25 become 1, etc. m <- c(0, 0.25, 1, 0.25, 0.5, 2, 0.5, 1, 3) rclmat <- matrix(m, ncol=3, byrow=TRUE) rc1 <- classify(r, rclmat, include.lowest=TRUE) ## cuts # equivalent to the above, but now a categorical SpatRaster is returned rc2 <- classify(r, c(0, 0.25, 0.5, 1), include.lowest=TRUE, brackets=TRUE) freq(rc2) ## is-becomes x <- round(r*3) unique(x) # replace 0 with NA y <- classify(x, cbind(0, NA)) unique(y) # multiple replacements m <- rbind(c(2, 200), c(3, 300)) m rcx1 <- classify(x, m) unique(rcx1) rcx2 <- classify(x, m, others=NA) unique(rcx2)
r <- rast(ncols=10, nrows=10) values(r) <- (0:99)/99 ## from-to-becomes # classify the values into three groups # all values >= 0 and <= 0.25 become 1, etc. m <- c(0, 0.25, 1, 0.25, 0.5, 2, 0.5, 1, 3) rclmat <- matrix(m, ncol=3, byrow=TRUE) rc1 <- classify(r, rclmat, include.lowest=TRUE) ## cuts # equivalent to the above, but now a categorical SpatRaster is returned rc2 <- classify(r, c(0, 0.25, 0.5, 1), include.lowest=TRUE, brackets=TRUE) freq(rc2) ## is-becomes x <- round(r*3) unique(x) # replace 0 with NA y <- classify(x, cbind(0, NA)) unique(y) # multiple replacements m <- rbind(c(2, 200), c(3, 300)) m rcx1 <- classify(x, m) unique(rcx1) rcx2 <- classify(x, m, others=NA) unique(rcx2)
Click on a map (plot) to get the coordinates or the values of a SpatRaster or SpatVector at that location. For a SpatRaster you can also get the coordinates and cell number of the location.
This does to work well on the default RStudio plotting device. To work around that, you can first run dev.new(noRStudioGD = TRUE)
which will create a separate window for plotting, then use plot()
followed by click()
and click on the map.
## S4 method for signature 'SpatRaster' click(x, n=10, id=FALSE, xy=FALSE, cell=FALSE, type="p", show=TRUE, ...) ## S4 method for signature 'SpatVector' click(x, n=10, id=FALSE, xy=FALSE, type="p", show=TRUE, ...) ## S4 method for signature 'missing' click(x, n=10, id=FALSE, type="p", show=TRUE, ...)
## S4 method for signature 'SpatRaster' click(x, n=10, id=FALSE, xy=FALSE, cell=FALSE, type="p", show=TRUE, ...) ## S4 method for signature 'SpatVector' click(x, n=10, id=FALSE, xy=FALSE, type="p", show=TRUE, ...) ## S4 method for signature 'missing' click(x, n=10, id=FALSE, type="p", show=TRUE, ...)
x |
SpatRaster or SpatVector, or missing |
n |
number of clicks on the plot (map) |
id |
logical. If |
xy |
logical. If |
cell |
logical. If |
type |
one of "n", "p", "l" or "o". If "p" or "o" the points are plotted; if "l" or "o" they are joined by lines. See |
show |
logical. Print the values after each click? |
... |
additional graphics parameters used if type != "n" for plotting the locations. See |
The value(s) of x
at the point(s) clicked on (or touched by the box drawn).
A data.frame
with the value(s) of all layers of SpatRaster x
for the cell(s) clicked on; or with the attributes of the geometries of SpatVector x
that intersect with the box drawn).
The plot only provides the coordinates for a spatial query, the values are read from the SpatRaster or SpatVector that is passed as an argument. Thus, you can extract values from an object that has not been plotted, as long as it spatially overlaps with the extent of the plot.
Unless the process is terminated prematurely values at most n
positions are determined. The identification process can be terminated, depending on how you interact with R, by hitting Esc, or by clicking the right mouse button and selecting "Stop" from the menu, or from the "Stop" menu on the graphics window.
## Not run: r <-rast(system.file("ex/elev.tif", package="terra")) plot(r) click(r, n=1) ## now click on the plot (map) ## End(Not run)
## Not run: r <-rast(system.file("ex/elev.tif", package="terra")) plot(r) click(r, n=1) ## now click on the plot (map) ## End(Not run)
Coercion of a SpatRaster to a vector, matrix or array. Or coerce a SpatExtent to a vector or matrix
## S4 method for signature 'SpatRaster' as.vector(x, mode='any') ## S4 method for signature 'SpatRaster' as.matrix(x, wide=FALSE, ...) ## S4 method for signature 'SpatRaster' as.array(x) ## S4 method for signature 'SpatExtent' as.vector(x, mode='any') ## S4 method for signature 'SpatExtent' as.matrix(x, ...)
## S4 method for signature 'SpatRaster' as.vector(x, mode='any') ## S4 method for signature 'SpatRaster' as.matrix(x, wide=FALSE, ...) ## S4 method for signature 'SpatRaster' as.array(x) ## S4 method for signature 'SpatExtent' as.vector(x, mode='any') ## S4 method for signature 'SpatExtent' as.matrix(x, ...)
x |
SpatRaster or SpatVector |
wide |
logical. If |
mode |
this argument is ignored |
... |
additional arguments (none implemented) |
vector, matrix, or array
r <- rast(ncols=2, nrows=2) values(r) <- 1:ncell(r) as.vector(r) as.matrix(r) as.matrix(r, wide=TRUE) as.data.frame(r, xy=TRUE) as.array(r) as.vector(ext(r)) as.matrix(ext(r))
r <- rast(ncols=2, nrows=2) values(r) <- 1:ncell(r) as.vector(r) as.matrix(r) as.matrix(r, wide=TRUE) as.data.frame(r, xy=TRUE) as.array(r) as.vector(ext(r)) as.matrix(ext(r))
Get or set color table(s) associated with a SpatRaster. Color tables are used for associating colors with values, for use in mapping (plot).
## S4 method for signature 'SpatRaster' coltab(x) ## S4 replacement method for signature 'SpatRaster' coltab(x, ..., layer=1)<-value ## S4 method for signature 'SpatRaster' has.colors(x)
## S4 method for signature 'SpatRaster' coltab(x) ## S4 replacement method for signature 'SpatRaster' coltab(x, ..., layer=1)<-value ## S4 method for signature 'SpatRaster' has.colors(x)
x |
SpatRaster |
layer |
positive integer, the layer number or name |
value |
a two-column data.frame (first column the cell value, the second column the color); a vector of colors (the first one is the color for value 0 and so on); or a four (value,red,green,blue) or five (including alpha) column data.frame also from 0 to n; or NULL to remove the color table. You can also supply a list of such data.frames to set a color table to all layers |
... |
additional arguments (none implemented) |
data.frame
r <- rast(ncols=3, nrows=2, vals=1:6) coltb <- data.frame(value=1:6, col=rainbow(6, end=.9)) coltb plot(r) has.colors(r) coltab(r) <- coltb plot(r) has.colors(r) tb <- coltab(r) class(tb) dim(tb[[1]])
r <- rast(ncols=3, nrows=2, vals=1:6) coltb <- data.frame(value=1:6, col=rainbow(6, end=.9)) coltb plot(r) has.colors(r) coltab(r) <- coltb plot(r) has.colors(r) tb <- coltab(r) class(tb) dim(tb[[1]])
Combine the geometries of one SpatVector with those of another. Geometries can be combined based on overlap, shared boundaries and distance (in that order of operation).
The typical use-case of this method is when you are editing geometries and you have a number of small polygons in one SpatVector that should be part of the geometries of the another SpatVector; perhaps because they were small holes inbetween the borders of two SpatVectors.
To append SpatVectors use 'rbind' and see methods like intersect
and union
for "normal" polygons combinations.
## S4 method for signature 'SpatVector,SpatVector' combineGeoms(x, y, overlap=TRUE, boundary=TRUE, distance=TRUE, append=TRUE, minover=0.1, maxdist=Inf, dissolve=TRUE, erase=TRUE)
## S4 method for signature 'SpatVector,SpatVector' combineGeoms(x, y, overlap=TRUE, boundary=TRUE, distance=TRUE, append=TRUE, minover=0.1, maxdist=Inf, dissolve=TRUE, erase=TRUE)
x |
SpatVector of polygons |
y |
SpatVector of polygons geometries that are to be combined with |
overlap |
logical. If |
boundary |
logical. If |
distance |
logical. If |
append |
logical. Should remaining geometries be appended to the output? Not relevant if |
minover |
numeric. The fraction of the geometry in |
maxdist |
numeric. Geometries further away from each other than this distance (in meters) will not be combined |
dissolve |
logical. Should internal boundaries be dissolved? |
erase |
logical. If |
SpatVector
x1 <- vect("POLYGON ((0 0, 8 0, 8 9, 0 9, 0 0))") x2 <- vect("POLYGON ((10 4, 12 4, 12 7, 11 7, 11 6, 10 6, 10 4))") y1 <- vect("POLYGON ((5 6, 15 6, 15 15, 5 15, 5 6))") y2 <- vect("POLYGON ((8 2, 9 2, 9 3, 8 3, 8 2))") y3 <- vect("POLYGON ((2 6, 3 6, 3 8, 2 8, 2 6))") y4 <- vect("POLYGON ((2 12, 3 12, 3 13, 2 13, 2 12))") x <- rbind(x1, x2) values(x) <- data.frame(xid=1:2) crs(x) <- "+proj=utm +zone=1" y <- rbind(y1, y2, y3, y4) values(y) <- data.frame(yid=letters[1:4]) crs(y) <- "+proj=utm +zone=1" plot(rbind(x, y), border=c(rep("red",2), rep("blue", 4)), lwd=2) text(x, "xid") text(y, "yid") v <- combineGeoms(x, y) plot(v, col=c("red", "blue")) v <- combineGeoms(x, y, boundary=FALSE, maxdist=1, minover=.05) plot(v, col=rainbow(4))
x1 <- vect("POLYGON ((0 0, 8 0, 8 9, 0 9, 0 0))") x2 <- vect("POLYGON ((10 4, 12 4, 12 7, 11 7, 11 6, 10 6, 10 4))") y1 <- vect("POLYGON ((5 6, 15 6, 15 15, 5 15, 5 6))") y2 <- vect("POLYGON ((8 2, 9 2, 9 3, 8 3, 8 2))") y3 <- vect("POLYGON ((2 6, 3 6, 3 8, 2 8, 2 6))") y4 <- vect("POLYGON ((2 12, 3 12, 3 13, 2 13, 2 12))") x <- rbind(x1, x2) values(x) <- data.frame(xid=1:2) crs(x) <- "+proj=utm +zone=1" y <- rbind(y1, y2, y3, y4) values(y) <- data.frame(yid=letters[1:4]) crs(y) <- "+proj=utm +zone=1" plot(rbind(x, y), border=c(rep("red",2), rep("blue", 4)), lwd=2) text(x, "xid") text(y, "yid") v <- combineGeoms(x, y) plot(v, col=c("red", "blue")) v <- combineGeoms(x, y, boundary=FALSE, maxdist=1, minover=.05) plot(v, col=rainbow(4))
Standard comparison and logical operators for computations with SpatRasters. Computations are local (applied on a cell by cell basis). If multiple SpatRasters are used, these must have the same geometry (extent and resolution). These operators have been implemented:
Logical: !, &, |, isTRUE, isFALSE
Compare: ==, !=, >, <, <=, >=, is.na, is.nan, is.finite, is.infinite
See not.na
for the inverse of is.na
, and noNA
to detect cells with missing value across layers.
The compare
and logic
methods implement these operators in a method that can return NA
istead of FALSE
and allows for setting an output filename.
The terra package does not distinguish between NA
(not available) and NaN
(not a number). In most cases this state is represented by NaN
.
If you use a SpatRaster with a vector of multiple numbers, each element in the vector is considered a layer (with a constant value). If you use a SpatRaster with a matrix, the number of columns of the matrix must match the number of layers of the SpatRaster. The rows are used to match the cells. That is, if there are two rows, these match cells 1 and 2, and they are recycled to 3 and 4, etc.
The following method has been implemented for (SpatExtent, SpatExtent): ==
## S4 method for signature 'SpatRaster' compare(x, y, oper, falseNA=FALSE, filename="", overwrite=FALSE, ...) ## S4 method for signature 'SpatRaster' logic(x, oper, falseNA=FALSE, filename="", overwrite=FALSE, ...)
## S4 method for signature 'SpatRaster' compare(x, y, oper, falseNA=FALSE, filename="", overwrite=FALSE, ...) ## S4 method for signature 'SpatRaster' logic(x, oper, falseNA=FALSE, filename="", overwrite=FALSE, ...)
x |
SpatRaster |
y |
SpatRaster or numeric |
oper |
character. Operator name. For |
falseNA |
logical. Should the result be |
filename |
character. Output filename |
overwrite |
logical. If |
... |
additional arguments for writing files as in |
SpatRaster or SpatExtent
all.equal
, Arith-methods. See ifel
to conveniently combine operations and Math-methods
or app
to apply any R function to a SpatRaster.
r1 <- rast(ncols=10, nrows=10) values(r1) <- runif(ncell(r1)) r1[10:20] <- NA r2 <- rast(r1) values(r2) <- 1:ncell(r2) / ncell(r2) x <- is.na(r1) !x r1 == r2 compare(r1, r2, "==") compare(r1, r2, "==", TRUE)
r1 <- rast(ncols=10, nrows=10) values(r1) <- runif(ncell(r1)) r1[10:20] <- NA r2 <- rast(r1) values(r2) <- 1:ncell(r2) / ncell(r2) x <- is.na(r1) !x r1 == r2 compare(r1, r2, "==") compare(r1, r2, "==", TRUE)
Evaluate whether two SpatRasters have the same extent, number of rows and columns, projection, resolution, and origin (or a subset of these comparisons).
Or evaluate whether two SpatVectors have the same geometries, or whether a SpatVector has duplicated geometries.
## S4 method for signature 'SpatRaster,SpatRaster' compareGeom(x, y, ..., lyrs=FALSE, crs=TRUE, warncrs=FALSE, ext=TRUE, rowcol=TRUE, res=FALSE, stopOnError=TRUE, messages=FALSE) ## S4 method for signature 'SpatVector,SpatVector' compareGeom(x, y, tolerance=0) ## S4 method for signature 'SpatVector,missing' compareGeom(x, y, tolerance=0)
## S4 method for signature 'SpatRaster,SpatRaster' compareGeom(x, y, ..., lyrs=FALSE, crs=TRUE, warncrs=FALSE, ext=TRUE, rowcol=TRUE, res=FALSE, stopOnError=TRUE, messages=FALSE) ## S4 method for signature 'SpatVector,SpatVector' compareGeom(x, y, tolerance=0) ## S4 method for signature 'SpatVector,missing' compareGeom(x, y, tolerance=0)
x |
SpatRaster or SpatVector |
y |
Same as |
... |
Additional SpatRasters |
lyrs |
logical. If |
crs |
logical. If |
warncrs |
logical. If |
ext |
logical. If |
rowcol |
logical. If |
res |
logical. If |
stopOnError |
logical. If |
messages |
logical. If |
tolerance |
numeric |
logical (SpatRaster) or matrix of logical (SpatVector)
r1 <- rast() r2 <- rast() r3 <- rast() compareGeom(r1, r2, r3) nrow(r3) <- 10 ## Not run: compareGeom(r1, r3) ## End(Not run)
r1 <- rast() r2 <- rast() r3 <- rast() compareGeom(r1, r2, r3) nrow(r3) <- 10 ## Not run: compareGeom(r1, r3) ## End(Not run)
Combine two categorical rasters by concatenating their levels.
## S4 method for signature 'SpatRaster' concats(x, y, filename="", ...)
## S4 method for signature 'SpatRaster' concats(x, y, filename="", ...)
x |
SpatRaster (with a single, categorical, layer) |
y |
SpatRaster (with a single, categorical, layer) |
filename |
character. Output filename |
... |
additional arguments for writing files as in |
SpatRaster
set.seed(0) r <- rast(nrows=10, ncols=10) values(r) <- sample(3, ncell(r), replace=TRUE) levels(r) <- data.frame(id=1:3, cover=c("forest", "water", "urban")) rr <- rast(r) values(rr) <- sample(1:3, ncell(rr), replace=TRUE) levels(rr) <- data.frame(id=c(1:3), color=c("red", "green", "blue")) x <- concats(r, rr) x levels(x)[[1]]
set.seed(0) r <- rast(nrows=10, ncols=10) values(r) <- sample(3, ncell(r), replace=TRUE) levels(r) <- data.frame(id=1:3, cover=c("forest", "water", "urban")) rr <- rast(r) values(rr) <- sample(1:3, ncell(rr), replace=TRUE) levels(rr) <- data.frame(id=c(1:3), color=c("red", "green", "blue")) x <- concats(r, rr) x levels(x)[[1]]
Contour lines (isolines) of a SpatRaster. Use add=TRUE
to add the lines to the current plot. See graphics::contour
for details.
if filled=TRUE
, a new filled contour plot is made. See graphics::filled.contour
for details.
as.contour
returns the contour lines as a SpatVector.
## S4 method for signature 'SpatRaster' contour(x, maxcells=100000, filled=FALSE, ...) ## S4 method for signature 'SpatRaster' as.contour(x, maxcells=100000, ...)
## S4 method for signature 'SpatRaster' contour(x, maxcells=100000, filled=FALSE, ...) ## S4 method for signature 'SpatRaster' as.contour(x, maxcells=100000, ...)
x |
SpatRaster. Only the first layer is used |
maxcells |
maximum number of pixels used to create the contours |
filled |
logical. If |
... |
any argument that can be passed to |
r <- rast(system.file("ex/elev.tif", package="terra")) plot(r) contour(r, add=TRUE) v <- as.contour(r) plot(r) lines(v) contour(r, filled=TRUE, nlevels=5) ## if you want a SpatVector with contour lines template <- disagg(rast(r), 10) rr <- resample(r, template) rr <- floor(rr/100) * 100 v <- as.polygons(rr) plot(v, 1, col=terrain.colors(7))
r <- rast(system.file("ex/elev.tif", package="terra")) plot(r) contour(r, add=TRUE) v <- as.contour(r) plot(r) lines(v) contour(r, filled=TRUE, nlevels=5) ## if you want a SpatVector with contour lines template <- disagg(rast(r), 10) rr <- resample(r, template) rr <- floor(rr/100) * 100 v <- as.polygons(rr) plot(v, 1, col=terrain.colors(7))
Get the convex hull, the minimal bounding rotated rectangle, or minimal bounding circle of a SpatVector
## S4 method for signature 'SpatVector' convHull(x, by="") ## S4 method for signature 'SpatVector' minRect(x, by="") ## S4 method for signature 'SpatVector' minCircle(x, by="")
## S4 method for signature 'SpatVector' convHull(x, by="") ## S4 method for signature 'SpatVector' minRect(x, by="") ## S4 method for signature 'SpatVector' minCircle(x, by="")
x |
SpatVector |
by |
character (variable name), to get a new geometry for groups of input geometries |
SpatVector
p <- vect(system.file("ex/lux.shp", package="terra")) h <- convHull(p) hh <- convHull(p, "NAME_1") rr <- minRect(p, "NAME_1") plot(rr, lwd=5, border="gray") plot(hh, "NAME_1", col=rainbow(10, alpha=.5), lwd=3, add=TRUE, plg=list(x="topright")) lines(aggregate(p, "NAME_1"), col="blue", lty=2, lwd=2)
p <- vect(system.file("ex/lux.shp", package="terra")) h <- convHull(p) hh <- convHull(p, "NAME_1") rr <- minRect(p, "NAME_1") plot(rr, lwd=5, border="gray") plot(hh, "NAME_1", col=rainbow(10, alpha=.5), lwd=3, add=TRUE, plg=list(x="topright")) lines(aggregate(p, "NAME_1"), col="blue", lty=2, lwd=2)
Use a friction (cost) surface to compute the cost-distance from any cell to the border of one or more target cells.
Distances are computed by summing local distances between cells, which are connected with their neighbors in 8 directions, and assuming that the path has to go through the centers of one of the neighboring raster cells.
Distances are multiplied with the friction, thus to get the cost-distance, the friction surface must express the cost per unit distance (speed) of travel.
## S4 method for signature 'SpatRaster' costDist(x, target=0, scale=1, maxiter=50, filename="", ...)
## S4 method for signature 'SpatRaster' costDist(x, target=0, scale=1, maxiter=50, filename="", ...)
x |
SpatRaster |
target |
numeric. value of the target cells (where to compute cost-distance to) |
scale |
numeric. Scale factor. The cost distance is divided by this number |
maxiter |
numeric. The maximum number of iterations. Increase this number if you get the warning that |
filename |
character. output filename (optional) |
... |
additional arguments as for |
SpatRaster
r <- rast(ncols=5, nrows=5, crs="+proj=utm +zone=1 +datum=WGS84", xmin=0, xmax=5, ymin=0, ymax=5, vals=1) r[13] <- 0 d <- costDist(r) plot(d) text(d, digits=1) r <- rast(ncols=10, nrows=10, xmin=0, xmax=10, ymin=0, ymax=10, vals=10, crs="+proj=utm +zone=1 +datum=WGS84") r[5, 1] <- -10 r[2:3, 1] <- r[1, 2:4] <- r[2, 5] <- 0 r[3, 6] <- r[2, 7] <- r[1, 8:9] <- 0 r[6, 6:10] <- NA r[6:9, 6] <- NA d <- costDist(r, -10) plot(d) text(d, digits=1, cex=.8)
r <- rast(ncols=5, nrows=5, crs="+proj=utm +zone=1 +datum=WGS84", xmin=0, xmax=5, ymin=0, ymax=5, vals=1) r[13] <- 0 d <- costDist(r) plot(d) text(d, digits=1) r <- rast(ncols=10, nrows=10, xmin=0, xmax=10, ymin=0, ymax=10, vals=10, crs="+proj=utm +zone=1 +datum=WGS84") r[5, 1] <- -10 r[2:3, 1] <- r[1, 2:4] <- r[2, 5] <- 0 r[3, 6] <- r[2, 7] <- r[1, 8:9] <- 0 r[6, 6:10] <- NA r[6:9, 6] <- NA d <- costDist(r, -10) plot(d) text(d, digits=1, cex=.8)
Replace NA
or other values in SpatRaster x
with the values of SpatRaster y
For polygons: areas of x
that overlap with y
are replaced by y
or, if identity=TRUE
intersected with y
.
## S4 method for signature 'SpatRaster,SpatRaster' cover(x, y, values=NA, filename="", ...) ## S4 method for signature 'SpatVector,SpatVector' cover(x, y, identity=FALSE, expand=TRUE)
## S4 method for signature 'SpatRaster,SpatRaster' cover(x, y, values=NA, filename="", ...) ## S4 method for signature 'SpatVector,SpatVector' cover(x, y, identity=FALSE, expand=TRUE)
x |
SpatRaster or SpatVector |
y |
Same as |
values |
numeric. The cell values in |
filename |
character. Output filename |
... |
additional arguments for writing files as in |
identity |
logical. If |
expand |
logical. Should parts of |
SpatRaster
r1 <- r2 <- rast(ncols=36, nrows=18) values(r1) <- 1:ncell(r1) values(r2) <- runif(ncell(r2)) r2 <- classify(r2, cbind(-Inf, 0.5, NA)) r3 <- cover(r2, r1) p <- vect(system.file("ex/lux.shp", package="terra")) e <- as.polygons(ext(6, 6.4, 49.75, 50)) values(e) <- data.frame(y=10) cv <- cover(p, e) plot(cv, col=rainbow(12)) ci <- cover(p, e, identity=TRUE) lines(e, lwd=3) plot(ci, col=rainbow(12)) lines(e, lwd=3)
r1 <- r2 <- rast(ncols=36, nrows=18) values(r1) <- 1:ncell(r1) values(r2) <- runif(ncell(r2)) r2 <- classify(r2, cbind(-Inf, 0.5, NA)) r3 <- cover(r2, r1) p <- vect(system.file("ex/lux.shp", package="terra")) e <- as.polygons(ext(6, 6.4, 49.75, 50)) values(e) <- data.frame(y=10) cv <- cover(p, e) plot(cv, col=rainbow(12)) ci <- cover(p, e, identity=TRUE) lines(e, lwd=3) plot(ci, col=rainbow(12)) lines(e, lwd=3)
Get the coordinates of a SpatVector or SpatRaster cells. A matrix or data.frame of the x (longitude) and y (latitude) coordinates is returned.
## S4 method for signature 'SpatVector' crds(x, df=FALSE, list=FALSE) ## S4 method for signature 'SpatRaster' crds(x, df=FALSE, na.rm=TRUE, na.all=FALSE)
## S4 method for signature 'SpatVector' crds(x, df=FALSE, list=FALSE) ## S4 method for signature 'SpatRaster' crds(x, df=FALSE, na.rm=TRUE, na.all=FALSE)
x |
SpatRaster or SpatVector |
df |
logical. If |
list |
logical. If |
na.rm |
logical. If |
na.all |
logical. If |
matrix or data.frame
geom
returns the complete structure of SpatVector geometries. For SpatRaster see xyFromCell
x1 <- rbind(c(-175,-20), c(-140,55), c(10, 0), c(-140,-60)) x2 <- rbind(c(-125,0), c(0,60), c(40,5), c(15,-45)) x3 <- rbind(c(-10,0), c(140,60), c(160,0), c(140,-55)) x4 <- rbind(c(80,0), c(105,13), c(120,2), c(105,-13)) z <- rbind(cbind(object=1, part=1, x1), cbind(object=2, part=1, x2), cbind(object=3, part=1, x3), cbind(object=3, part=2, x4)) colnames(z)[3:4] <- c('x', 'y') z <- cbind(z, hole=0) z[(z[, "object"]==3 & z[,"part"]==2), "hole"] <- 1 p <- vect(z, "polygons") crds(p) f <- system.file("ex/lux.shp", package="terra") v <- vect(f) g <- crds(v) head(g)
x1 <- rbind(c(-175,-20), c(-140,55), c(10, 0), c(-140,-60)) x2 <- rbind(c(-125,0), c(0,60), c(40,5), c(15,-45)) x3 <- rbind(c(-10,0), c(140,60), c(160,0), c(140,-55)) x4 <- rbind(c(80,0), c(105,13), c(120,2), c(105,-13)) z <- rbind(cbind(object=1, part=1, x1), cbind(object=2, part=1, x2), cbind(object=3, part=1, x3), cbind(object=3, part=2, x4)) colnames(z)[3:4] <- c('x', 'y') z <- cbind(z, hole=0) z[(z[, "object"]==3 & z[,"part"]==2), "hole"] <- 1 p <- vect(z, "polygons") crds(p) f <- system.file("ex/lux.shp", package="terra") v <- vect(f) g <- crds(v) head(g)
Cut out a part of a SpatRaster or SpatVector.
You can crop a SpatRaster with a SpatExtent, or with another object from which an extent can be obtained. Note that the SpatRaster returned may not have the exactly the same extent as the SpatExtent supplied because you can only select entire cells (rows and columns), and you cannot add new areas. See methods like resample
and disagg
to force SpatRasters to align and extend
to add rows and/or columns.
You can only crop rectangular areas of a SpatRaster, but see argument mask=TRUE
for setting cell values within SpatRaster to NA
; or use the mask
method after crop for additional masking options.
You can crop a SpatVector with another SpatVector. If these are not polygons, the minimum convex hull is used. Unlike with intersect
the geometries and attributes of y
are not transferred to the output. You can also crop a SpatVector with a rectangle (SpatRaster, SpatExtent).
## S4 method for signature 'SpatRaster' crop(x, y, snap="near", mask=FALSE, touches=TRUE, extend=FALSE, filename="", ...) ## S4 method for signature 'SpatRasterDataset' crop(x, y, snap="near", extend=FALSE) ## S4 method for signature 'SpatRasterCollection' crop(x, y, snap="near", extend=FALSE) ## S4 method for signature 'SpatVector' crop(x, y, ext=FALSE) ## S4 method for signature 'SpatGraticule' crop(x, y)
## S4 method for signature 'SpatRaster' crop(x, y, snap="near", mask=FALSE, touches=TRUE, extend=FALSE, filename="", ...) ## S4 method for signature 'SpatRasterDataset' crop(x, y, snap="near", extend=FALSE) ## S4 method for signature 'SpatRasterCollection' crop(x, y, snap="near", extend=FALSE) ## S4 method for signature 'SpatVector' crop(x, y, ext=FALSE) ## S4 method for signature 'SpatGraticule' crop(x, y)
x |
SpatRaster or SpatVector |
y |
SpatRaster, SpatVector, SpatExtent, or any other object that has a SpatExtent ( |
snap |
character. One of "near", "in", or "out". Used to align |
mask |
logical. Should |
touches |
logical. If |
extend |
logical. Should rows and/or columns be added if |
filename |
character. Output filename |
... |
additional arguments for writing files as in |
ext |
logical. Use the extent of |
SpatRaster
See window
for a virtual and sometimes more efficient way to crop a dataset.
r <- rast(xmin=0, xmax=10, ymin=0, ymax=10, nrows=25, ncols=25) values(r) <- 1:ncell(r) e <- ext(-5, 5, -5, 5) rc <- crop(r, e) # crop and mask f <- system.file("ex/elev.tif", package="terra") r <- rast(f) f <- system.file("ex/lux.shp", package="terra") v <- vect(f) cm <- crop(r, v[9:12,], mask=TRUE) plot(cm) lines(v) # crop vector f <- system.file("ex/lux.shp", package="terra") v <- vect(f) e <- ext(6.15, 6.3, 49.7, 49.8) x <- crop(v, e) plot(x, "NAME_1")
r <- rast(xmin=0, xmax=10, ymin=0, ymax=10, nrows=25, ncols=25) values(r) <- 1:ncell(r) e <- ext(-5, 5, -5, 5) rc <- crop(r, e) # crop and mask f <- system.file("ex/elev.tif", package="terra") r <- rast(f) f <- system.file("ex/lux.shp", package="terra") v <- vect(f) cm <- crop(r, v[9:12,], mask=TRUE) plot(cm) lines(v) # crop vector f <- system.file("ex/lux.shp", package="terra") v <- vect(f) e <- ext(6.15, 6.3, 49.7, 49.8) x <- crop(v, e) plot(x, "NAME_1")
Cross-tabulate the layers of a SpatRaster to create a contingency table.
## S4 method for signature 'SpatRaster,missing' crosstab(x, digits=0, long=FALSE, useNA=FALSE)
## S4 method for signature 'SpatRaster,missing' crosstab(x, digits=0, long=FALSE, useNA=FALSE)
x |
SpatRaster |
digits |
integer. The number of digits for rounding the values before cross-tabulation |
long |
logical. If |
useNA |
logical, indicting if the table should includes counts of |
A table or data.frame
r <- s <- rast(nc=5, nr=5) set.seed(1) values(r) <- runif(ncell(r)) * 2 values(s) <- runif(ncell(r)) * 3 x <- c(r, s) crosstab(x) rs <- r/s r[1:5] <- NA s[20:25] <- NA x <- c(r, s, rs) crosstab(x, useNA=TRUE, long=TRUE)
r <- s <- rast(nc=5, nr=5) set.seed(1) values(r) <- runif(ncell(r)) * 2 values(s) <- runif(ncell(r)) * 3 x <- c(r, s) crosstab(x) rs <- r/s r[1:5] <- NA s[20:25] <- NA x <- c(r, s, rs) crosstab(x, useNA=TRUE, long=TRUE)
Get or set the coordinate reference system (CRS), also referred to as a "projection", of a SpatRaster or SpatVector.
Setting a new CRS does not change the data itself, it just changes the label. So you should only set the CRS of a dataset (if it does not come with one) to what it *is*, not to what you would *like it to be*. See project
to *transform* an object from one CRS to another.
## S4 method for signature 'SpatRaster' crs(x, proj=FALSE, describe=FALSE, parse=FALSE) ## S4 method for signature 'SpatVector' crs(x, proj=FALSE, describe=FALSE, parse=FALSE) ## S4 method for signature 'character' crs(x, proj=FALSE, describe=FALSE, parse=FALSE) ## S4 replacement method for signature 'SpatRaster' crs(x, warn=FALSE)<-value ## S4 replacement method for signature 'SpatVector' crs(x, warn=FALSE)<-value
## S4 method for signature 'SpatRaster' crs(x, proj=FALSE, describe=FALSE, parse=FALSE) ## S4 method for signature 'SpatVector' crs(x, proj=FALSE, describe=FALSE, parse=FALSE) ## S4 method for signature 'character' crs(x, proj=FALSE, describe=FALSE, parse=FALSE) ## S4 replacement method for signature 'SpatRaster' crs(x, warn=FALSE)<-value ## S4 replacement method for signature 'SpatVector' crs(x, warn=FALSE)<-value
x |
SpatRaster or SpatVector |
proj |
logical. If |
describe |
logical. If |
warn |
logical. If |
value |
character string describing a coordinate reference system. This can be in a WKT format, as a <authority:number> code such as "EPSG:4326", or a PROJ-string format such as "+proj=utm +zone=12" (see Note) |
parse |
logical. If |
character or modified SpatRaster/Vector
Projections are handled by the PROJ/GDAL libraries. The PROJ developers suggest to define a CRS with the WKT2 or <authority>:<code> notation. It is not practical to define one's own custom CRS with WKT2, and the the <authority>:<code> system only covers a handful of (commonly used) CRSs. To work around this problem it is still possible to use the deprecated PROJ-string notation (+proj=...
) with one major caveat: the datum should be WGS84 (or the equivalent NAD83) – if you want to transform your data to a coordinate reference system with a different datum. Thus as long as you use WGS84, or an ellipsoid instead of a datum, you can safely use PROJ-strings to represent your CRS; including to define your own custom CRS.
You can also set the crs to "local" to get an informal coordinate system on an arbitrary Euclidean (Cartesian) plane with units in meter.
r <- rast() crs(r) crs(r, describe=TRUE, proj=TRUE) crs(r) <- "+proj=lcc +lat_1=48 +lat_2=33 +lon_0=-100 +ellps=WGS84" crs(r) # You can use epsg codes crs(r) <- "epsg:25831" crs(r, describe=TRUE)$area crs("epsg:25831", describe=TRUE)
r <- rast() crs(r) crs(r, describe=TRUE, proj=TRUE) crs(r) <- "+proj=lcc +lat_1=48 +lat_2=33 +lon_0=-100 +ellps=WGS84" crs(r) # You can use epsg codes crs(r) <- "epsg:25831" crs(r, describe=TRUE)$area crs("epsg:25831", describe=TRUE)
Get the data types of the fields (attributes, variables) of a SpatVector or of the file(s) associated with a SpatRaster. A (layer of a) SpatRaster has no datatype if it has no values, or if the values are in memory.
## S4 method for signature 'SpatRaster' datatype(x, bylyr=TRUE) ## S4 method for signature 'SpatVector' datatype(x)
## S4 method for signature 'SpatRaster' datatype(x, bylyr=TRUE) ## S4 method for signature 'SpatVector' datatype(x)
x |
SpatRaster or SpatVector |
bylyr |
logical. If |
character
Raster data types
to check / set the type of SpatRaster values.
f <- system.file("ex/lux.shp", package="terra") v <- vect(f) datatype(v) f <- system.file("ex/elev.tif", package="terra") r <- rast(f) datatype(r) # no data type datatype(rast())
f <- system.file("ex/lux.shp", package="terra") v <- vect(f) datatype(v) f <- system.file("ex/elev.tif", package="terra") r <- rast(f) datatype(r) # no data type datatype(rast())
Make a deep copy of a SpatRaster or SpatVector. This is occasionally useful when wanting to use a replacement function in a shallow copy. That is a copy that was created like this: x <- y
. If you use a replacement function to change an object, its shallow copies also change.
## S4 method for signature 'SpatRaster' deepcopy(x) ## S4 method for signature 'SpatVector' deepcopy(x)
## S4 method for signature 'SpatRaster' deepcopy(x) ## S4 method for signature 'SpatVector' deepcopy(x)
x |
SpatRaster or SpatVector |
Same as x
r <- rast(ncols=10, nrows=10, nl=3) tm <- as.Date("2001-05-03") + 1:3 time(r) <- tm time(r) x <- r time(x) <- tm + 365 time(x) time(r) y <- deepcopy(r) time(y) <- tm - 365 time(y) time(r) # or make a new object like this z <- rast(r) time(z) <- tm time(z) time(r)
r <- rast(ncols=10, nrows=10, nl=3) tm <- as.Date("2001-05-03") + 1:3 time(r) <- tm time(r) x <- r time(x) <- tm + 365 time(x) time(r) y <- deepcopy(r) time(y) <- tm - 365 time(y) time(r) # or make a new object like this z <- rast(r) time(z) <- tm time(z) time(r)
Add additional nodes to lines or polygons. This can be useful to do prior to using project
such that the path does not change too much.
## S4 method for signature 'SpatVector' densify(x, interval, equalize=TRUE, flat=FALSE)
## S4 method for signature 'SpatVector' densify(x, interval, equalize=TRUE, flat=FALSE)
x |
SpatVector |
interval |
positive number, specifying the desired minimum distance between nodes. The unit is meter for lonlat data, and in the linear unit of the crs for planar data |
equalize |
logical. If |
flat |
logical. If |
SpatVector
v <- vect(rbind(c(-120,-20), c(-80,5), c(-40,-60), c(-120,-20)), type="polygons", crs="+proj=longlat") vd <- densify(v, 200000) p <- project(v, "+proj=robin") pd <- project(vd, "+proj=robin") # good plot(pd, col="gray", border="red", lwd=10) points(pd, col="gray") # bad lines(p, col="blue", lwd=3) points(p, col="blue", cex=2) plot(p, col="blue", alpha=.1, add=TRUE) legend("topright", c("good", "bad"), col=c("red", "blue"), lty=1, lwd=3) ## the other way around does not work ## unless the original data was truly planar (e.g. derived from a map) x <- densify(p, 250000) y <- project(x, "+proj=longlat") # bad plot(y) # good lines(vd, col="red")
v <- vect(rbind(c(-120,-20), c(-80,5), c(-40,-60), c(-120,-20)), type="polygons", crs="+proj=longlat") vd <- densify(v, 200000) p <- project(v, "+proj=robin") pd <- project(vd, "+proj=robin") # good plot(pd, col="gray", border="red", lwd=10) points(pd, col="gray") # bad lines(p, col="blue", lwd=3) points(p, col="blue", cex=2) plot(p, col="blue", alpha=.1, add=TRUE) legend("topright", c("good", "bad"), col=c("red", "blue"), lty=1, lwd=3) ## the other way around does not work ## unless the original data was truly planar (e.g. derived from a map) x <- densify(p, 250000) y <- project(x, "+proj=longlat") # bad plot(y) # good lines(vd, col="red")
Create density plots of the cell values of a SpatRaster
## S4 method for signature 'SpatRaster' density(x, maxcells=100000, plot=TRUE, main, ...)
## S4 method for signature 'SpatRaster' density(x, maxcells=100000, plot=TRUE, main, ...)
x |
SpatRaster |
maxcells |
the maximum number of (randomly sampled) cells to be used for creating the plot |
plot |
if |
main |
character. Caption of plot(s) |
... |
additional arguments passed to |
density plot (and a density object, returned invisibly if plot=TRUE)
logo <- rast(system.file("ex/logo.tif", package="terra")) density(logo)
logo <- rast(system.file("ex/logo.tif", package="terra")) density(logo)
These methods are deprecated and will be removed in future versions
## S4 method for signature 'SpatRaster' setCats(x, ...) ## S4 method for signature 'SpatRaster' area(x, ...)
## S4 method for signature 'SpatRaster' setCats(x, ...) ## S4 method for signature 'SpatRaster' area(x, ...)
x |
object |
... |
additional arguments |
Get or set the depth of the layers of a SpatRaster. Experimental.
## S4 method for signature 'SpatRaster' depth(x) ## S4 replacement method for signature 'SpatRaster' depth(x)<-value
## S4 method for signature 'SpatRaster' depth(x) ## S4 replacement method for signature 'SpatRaster' depth(x)<-value
x |
SpatRaster |
value |
numeric vector |
numeric
s <- rast(system.file("ex/logo.tif", package="terra")) depth(s) <- 1:3 depth(s)
s <- rast(system.file("ex/logo.tif", package="terra")) depth(s) <- 1:3 depth(s)
Describe the properties of spatial data in a file as generated with the "GDALinfo" tool.
## S4 method for signature 'character' describe(x, sds=FALSE, meta=FALSE, parse=FALSE, options="", print=FALSE, open_opt="")
## S4 method for signature 'character' describe(x, sds=FALSE, meta=FALSE, parse=FALSE, options="", print=FALSE, open_opt="")
x |
character. The name of a file with spatial data. Or a fully specified subdataset within a file such as |
sds |
logical. If |
meta |
logical. Get the file level metadata instead |
parse |
logical. If |
options |
character. A vector of valid options (if |
print |
logical. If |
open_opt |
character. Driver specific open options |
character (invisibly, if print=FALSE
)
f <- system.file("ex/elev.tif", package="terra") describe(f) describe(f, meta=TRUE) #g <- describe(f, options=c("json", "nomd", "proj4")) #head(g)
f <- system.file("ex/elev.tif", package="terra") describe(f) describe(f, meta=TRUE) #g <- describe(f, options=c("json", "nomd", "proj4")) #head(g)
Compute the difference between consecutive layers in a SpatRaster.
## S4 method for signature 'SpatRaster' diff(x, lag=1, filename="", ...)
## S4 method for signature 'SpatRaster' diff(x, lag=1, filename="", ...)
x |
SpatRaster |
lag |
positive integer indicating which lag to use |
filename |
character. Output filename |
... |
additional arguments for writing files as in |
SpatRaster
s <- rast(system.file("ex/logo.tif", package="terra")) d <- diff(s)
s <- rast(system.file("ex/logo.tif", package="terra")) d <- diff(s)
Get the number of rows (nrow
), columns (ncol
), cells (ncell
), layers (nlyr
), sources (nsrc
), the size size
(nlyr(x)*ncell(x)
), or spatial resolution of a SpatRaster.
length
returns the number of sub-datasets in a SpatRasterDataset or SpatVectorCollection.
For a SpatVector length(x)
is the same as nrow(x)
.
You can also set the number of rows or columns or layers. When setting dimensions, all cell values are dropped.
## S4 method for signature 'SpatRaster' ncol(x) ## S4 method for signature 'SpatRaster' nrow(x) ## S4 method for signature 'SpatRaster' nlyr(x) ## S4 method for signature 'SpatRaster' ncell(x) ## S4 method for signature 'SpatRaster' nsrc(x) ## S4 replacement method for signature 'SpatRaster,numeric' ncol(x)<-value ## S4 replacement method for signature 'SpatRaster,numeric' nrow(x)<-value ## S4 replacement method for signature 'SpatRaster,numeric' nlyr(x)<-value ## S4 method for signature 'SpatRaster' res(x) ## S4 replacement method for signature 'SpatRaster,numeric' res(x)<-value ## S4 method for signature 'SpatRaster' xres(x) ## S4 method for signature 'SpatRaster' yres(x) ## S4 method for signature 'SpatVector' ncol(x) ## S4 method for signature 'SpatVector' nrow(x) ## S4 method for signature 'SpatVector' length(x)
## S4 method for signature 'SpatRaster' ncol(x) ## S4 method for signature 'SpatRaster' nrow(x) ## S4 method for signature 'SpatRaster' nlyr(x) ## S4 method for signature 'SpatRaster' ncell(x) ## S4 method for signature 'SpatRaster' nsrc(x) ## S4 replacement method for signature 'SpatRaster,numeric' ncol(x)<-value ## S4 replacement method for signature 'SpatRaster,numeric' nrow(x)<-value ## S4 replacement method for signature 'SpatRaster,numeric' nlyr(x)<-value ## S4 method for signature 'SpatRaster' res(x) ## S4 replacement method for signature 'SpatRaster,numeric' res(x)<-value ## S4 method for signature 'SpatRaster' xres(x) ## S4 method for signature 'SpatRaster' yres(x) ## S4 method for signature 'SpatVector' ncol(x) ## S4 method for signature 'SpatVector' nrow(x) ## S4 method for signature 'SpatVector' length(x)
x |
SpatRaster or SpatVector or related objects |
value |
For ncol and nrow: positive integer. For res: one or two positive numbers |
integer
r <- rast() ncol(r) nrow(r) nlyr(r) dim(r) nsrc(r) ncell(r) rr <- c(r,r) nlyr(rr) nsrc(rr) ncell(rr) nrow(r) <- 18 ncol(r) <- 36 # equivalent to dim(r) <- c(18, 36) dim(r) dim(r) <- c(10, 10, 5) dim(r) xres(r) yres(r) res(r) res(r) <- 1/120 # different xres and yres res(r) <- c(1/120, 1/60)
r <- rast() ncol(r) nrow(r) nlyr(r) dim(r) nsrc(r) ncell(r) rr <- c(r,r) nlyr(rr) nsrc(rr) ncell(rr) nrow(r) <- 18 ncol(r) <- 36 # equivalent to dim(r) <- c(18, 36) dim(r) dim(r) <- c(10, 10, 5) dim(r) xres(r) yres(r) res(r) res(r) <- 1/120 # different xres and yres res(r) <- c(1/120, 1/60)
The direction (azimuth) to or from the nearest cell that is not NA
. The direction is expressed in radians, unless you use argument degrees=TRUE
.
## S4 method for signature 'SpatRaster' direction(x, from=FALSE, degrees=FALSE, filename="", ...)
## S4 method for signature 'SpatRaster' direction(x, from=FALSE, degrees=FALSE, filename="", ...)
x |
SpatRaster |
filename |
Character. Output filename (optional) |
degrees |
Logical. If |
from |
Logical. Default is |
... |
Additional arguments as for |
SpatRaster
r <- rast(ncol=36,nrow=18, crs="+proj=merc") values(r) <- NA r[306] <- 1 b <- direction(r, degrees=TRUE) plot(b) crs(r) <- "+proj=longlat" b <- direction(r) plot(b)
r <- rast(ncol=36,nrow=18, crs="+proj=merc") values(r) <- NA r[306] <- 1 b <- direction(r, degrees=TRUE) plot(b) crs(r) <- "+proj=longlat" b <- direction(r) plot(b)
SpatRaster
: Create a SpatRaster with a higher resolution (smaller cells). The values in the new SpatRaster are the same as in the larger original cells.
SpatVector
: Separate multi-objects (points, lines, polygons) into single objects; or further into segments (for lines or polygons).
## S4 method for signature 'SpatRaster' disagg(x, fact, method="near", filename="", ...) ## S4 method for signature 'SpatVector' disagg(x, segments=FALSE)
## S4 method for signature 'SpatRaster' disagg(x, fact, method="near", filename="", ...) ## S4 method for signature 'SpatVector' disagg(x, segments=FALSE)
x |
SpatRaster or SpatVector |
fact |
positive integer. Aggregation factor expressed as number of cells in each direction (horizontally and vertically). Or two integers (horizontal and vertical aggregation factor) or three integers (when also aggregating over layers) |
method |
character. Either "near" for nearest or "bilinear" for bilinear interpolation |
segments |
logical. Should (poly-)lines or polygons be disaggregated into their line-segments? |
filename |
character. Output filename |
... |
additional arguments for writing files as in |
SpatRaster
r <- rast(ncols=10, nrows=10) rd <- disagg(r, fact=c(10, 2)) ncol(rd) nrow(rd) values(r) <- 1:ncell(r) rd <- disagg(r, fact=c(4, 2))
r <- rast(ncols=10, nrows=10) rd <- disagg(r, fact=c(10, 2)) ncol(rd) nrow(rd) values(r) <- 1:ncell(r) rd <- disagg(r, fact=c(4, 2))
If x
is a SpatRaster:
If y
is missing
this method computes the distance, for all cells that are NA
in SpatRaster x
to the nearest cell that is not NA
(or other values, see arguments "target" and "exclude").
If y
is a numeric value, the cells with that value are ignored. That is, distance to or from these cells is not computed (only if grid=FALSE
).
If y
is a SpatVector, the distance to that SpatVector is computed for all cells. For lines and polygons this is done after rasterization; and only the overlapping areas of the vector and raster are considered (for now).
The distance is always expressed in meter if the coordinate reference system is longitude/latitude, and in map units otherwise. Map units are typically meter, but inspect crs(x)
if in doubt.
Results are more precise, sometimes much more precise, when using longitude/latitude rather than a planar coordinate reference system, as these distort distance.
If x
is a SpatVector:
If y
is missing
, a distance matrix between all objects in x
is computed. A distance matrix object of class "dist" is returned.
If y
is a SpatVector the geographic distance between all objects is computed (and a matrix is returned). If both sets have the same number of points, and pairwise=TRUE
, the distance between each pair of objects is computed, and a vector is returned.
The distance is always expressed in meter, except when the coordinate reference system is longitude/latitude AND one of the SpatVector(s) consists of lines or polygons. In that case the distance is in degrees, and thus not very useful (this will be fixed soon). Otherwise, results are more precise, sometimes much more precise, when using longitude/latitude rather than a planar coordinate reference system, as these distort distance.
If x
is a matrix:
x
should consist of two columns, the first with "x" (or longitude) and the second with "y" coordinates (or latitude). If y
is a also a matrix, the distance between each points in x
and all points in y
is computed, unless pairwise=TRUE
If y
is missing, the distance between each points in x
with all other points in x
is computed, unless sequential=TRUE
## S4 method for signature 'SpatRaster,missing' distance(x, y, target=NA, exclude=NULL, unit="m", haversine=TRUE, filename="", ...) ## S4 method for signature 'SpatRaster,SpatVector' distance(x, y, unit="m", rasterize=FALSE, haversine=TRUE, filename="", ...) ## S4 method for signature 'SpatVector,ANY' distance(x, y, sequential=FALSE, pairs=FALSE, symmetrical=TRUE, unit="m") ## S4 method for signature 'SpatVector,SpatVector' distance(x, y, pairwise=FALSE, unit="m") ## S4 method for signature 'matrix,matrix' distance(x, y, lonlat, pairwise=FALSE, unit="m") ## S4 method for signature 'matrix,missing' distance(x, y, lonlat, sequential=FALSE, pairs=FALSE, symmetrical=TRUE, unit="m")
## S4 method for signature 'SpatRaster,missing' distance(x, y, target=NA, exclude=NULL, unit="m", haversine=TRUE, filename="", ...) ## S4 method for signature 'SpatRaster,SpatVector' distance(x, y, unit="m", rasterize=FALSE, haversine=TRUE, filename="", ...) ## S4 method for signature 'SpatVector,ANY' distance(x, y, sequential=FALSE, pairs=FALSE, symmetrical=TRUE, unit="m") ## S4 method for signature 'SpatVector,SpatVector' distance(x, y, pairwise=FALSE, unit="m") ## S4 method for signature 'matrix,matrix' distance(x, y, lonlat, pairwise=FALSE, unit="m") ## S4 method for signature 'matrix,missing' distance(x, y, lonlat, sequential=FALSE, pairs=FALSE, symmetrical=TRUE, unit="m")
x |
SpatRaster, SpatVector, or two-column matrix with coordinates (x,y) or (lon,lat) |
y |
missing, numeric, SpatVector, or two-column matrix |
target |
numeric. The value of the cells for which distances to cells that are not |
exclude |
numeric. The value of the cells that should not be considered for computing distances |
unit |
character. Can be either "m" or "km" |
haversine |
logical. Use the haversine formula for lon/lat data use the haversine formula? If |
rasterize |
logical. If |
filename |
character. Output filename |
... |
additional arguments for writing files as in |
sequential |
logical. If |
pairwise |
logical. If |
lonlat |
logical. If |
pairs |
logical. If |
symmetrical |
logical. If |
SpatRaster or numeric or matrix or distance matrix (object of class "dist")
A distance matrix can be coerced into a regular matrix with as.matrix
Karney, C.F.F., 2013. Algorithms for geodesics, J. Geodesy 87: 43-55. doi:10.1007/s00190-012-0578-z.
#lonlat r <- rast(ncols=36, nrows=18, crs="+proj=longlat +datum=WGS84") r[500] <- 1 d <- distance(r) plot(d / 100000) #planar rr <- rast(ncols=36, nrows=18, crs="+proj=utm +zone=1 +datum=WGS84") rr[500] <- 1 d <- distance(rr) rr[3:10, 3:10] <- 99 e <- distance(rr, exclude=99) p1 <- vect(rbind(c(0,0), c(90,30), c(-90,-30)), crs="+proj=longlat +datum=WGS84") dp <- distance(r, p1) d <- distance(p1) d as.matrix(d) p2 <- vect(rbind(c(30,-30), c(25,40), c(-9,-3)), crs="+proj=longlat +datum=WGS84") dd <- distance(p1, p2) dd pd <- distance(p1, p2, pairwise=TRUE) pd pd == diag(dd) # polygons, lines crs <- "+proj=utm +zone=1" p1 <- vect("POLYGON ((0 0, 8 0, 8 9, 0 9, 0 0))", crs=crs) p2 <- vect("POLYGON ((5 6, 15 6, 15 15, 5 15, 5 6))", crs=crs) p3 <- vect("POLYGON ((2 12, 3 12, 3 13, 2 13, 2 12))", crs=crs) p <- rbind(p1, p2, p3) L1 <- vect("LINESTRING(1 11, 4 6, 10 6)", crs=crs) L2 <- vect("LINESTRING(8 14, 12 10)", crs=crs) L3 <- vect("LINESTRING(1 8, 12 14)", crs=crs) lns <- rbind(L1, L2, L3) pts <- vect(cbind(c(7,10,10), c(3,5,6)), crs=crs) distance(p1,p3) distance(p) distance(p,pts) distance(p,lns) distance(pts,lns)
#lonlat r <- rast(ncols=36, nrows=18, crs="+proj=longlat +datum=WGS84") r[500] <- 1 d <- distance(r) plot(d / 100000) #planar rr <- rast(ncols=36, nrows=18, crs="+proj=utm +zone=1 +datum=WGS84") rr[500] <- 1 d <- distance(rr) rr[3:10, 3:10] <- 99 e <- distance(rr, exclude=99) p1 <- vect(rbind(c(0,0), c(90,30), c(-90,-30)), crs="+proj=longlat +datum=WGS84") dp <- distance(r, p1) d <- distance(p1) d as.matrix(d) p2 <- vect(rbind(c(30,-30), c(25,40), c(-9,-3)), crs="+proj=longlat +datum=WGS84") dd <- distance(p1, p2) dd pd <- distance(p1, p2, pairwise=TRUE) pd pd == diag(dd) # polygons, lines crs <- "+proj=utm +zone=1" p1 <- vect("POLYGON ((0 0, 8 0, 8 9, 0 9, 0 0))", crs=crs) p2 <- vect("POLYGON ((5 6, 15 6, 15 15, 5 15, 5 6))", crs=crs) p3 <- vect("POLYGON ((2 12, 3 12, 3 13, 2 13, 2 12))", crs=crs) p <- rbind(p1, p2, p3) L1 <- vect("LINESTRING(1 11, 4 6, 10 6)", crs=crs) L2 <- vect("LINESTRING(8 14, 12 10)", crs=crs) L3 <- vect("LINESTRING(1 8, 12 14)", crs=crs) lns <- rbind(L1, L2, L3) pts <- vect(cbind(c(7,10,10), c(3,5,6)), crs=crs) distance(p1,p3) distance(p) distance(p,pts) distance(p,lns) distance(pts,lns)
Create the dots for a dot-density map and add these to the current map. Dot-density maps are made to display count data. For example of population counts, where each dot represents n persons. The dots are returned as a SpatVector
. It there is an active graphics device, the dots are added to it with points
.
## S4 method for signature 'SpatVector' dots(x, field, size, ...)
## S4 method for signature 'SpatVector' dots(x, field, size, ...)
x |
SpatVector |
field |
character of numeric indicating field name. Or numeric vector of the same length as |
size |
positive number indicating the number of cases associated with each dot |
... |
graphical arguments passed to |
SpatVector (invisibly)
f <- system.file("ex/lux.shp", package="terra") v <- vect(f) v$population <- 1000*(1:12)^2 plot(v, lwd=3, col="light gray", border="white") d <- dots(v, "population", 1000, col="red", cex=.75) lines(v) d
f <- system.file("ex/lux.shp", package="terra") v <- vect(f) v$population <- 1000*(1:12)^2 plot(v, lwd=3, col="light gray", border="white") d <- dots(v, "population", 1000, col="red", cex=.75) lines(v) d
Draw on a plot (map) to get a SpatVector or SpatExtent object for later use. After calling the function, start clicking on the map. When you are done, press ESC
. You can also preset the maximum number of clicks.
This does to work well on the default RStudio plotting device. To work around that, you can first run dev.new(noRStudioGD = TRUE)
which will create a separate window for plotting, then use plot()
followed by click()
and click on the map.
## S4 method for signature 'character' draw(x="extent", col="red", lwd=2, id=FALSE, n=1000, xpd=TRUE, ...)
## S4 method for signature 'character' draw(x="extent", col="red", lwd=2, id=FALSE, n=1000, xpd=TRUE, ...)
x |
character. The type of object to draw. One of "extent", "polygon", "line", or "points" |
col |
the color to be used |
lwd |
the width of the lines to be drawn |
id |
logical. If |
n |
the maximum number of clicks (does not apply when |
xpd |
logical. If |
... |
additional graphics arguments for drawing |
SpatVector or SpatExtent
Elongate SpatVector lines
## S4 method for signature 'SpatVector' elongate(x, length=1, flat=FALSE)
## S4 method for signature 'SpatVector' elongate(x, length=1, flat=FALSE)
x |
SpatVector |
length |
positive number indicating how much the lines should be elongated at each end. The unit is meter is the crs is lonlat and it is the same as the linear unit of the crs on other cases (also meter in most cases) |
flat |
logical. If |
SpatVector
v <- vect(cbind(c(0,1,2), c(0,0,2)), "lines", crs="lonlat") e <- elongate(v, 100000) plot(e) points(e) geom(e)
v <- vect(cbind(c(0,1,2), c(0,0,2)), "lines", crs="lonlat") e <- elongate(v, 100000) plot(e) points(e) geom(e)
Erase parts of a SpatVector with another SpatVector or with a SpatExtent. You can also erase (parts of) polygons with the other polygons of the same SpatVector.
## S4 method for signature 'SpatVector,SpatVector' erase(x, y) ## S4 method for signature 'SpatVector,missing' erase(x, sequential=TRUE) ## S4 method for signature 'SpatVector,SpatExtent' erase(x, y)
## S4 method for signature 'SpatVector,SpatVector' erase(x, y) ## S4 method for signature 'SpatVector,missing' erase(x, sequential=TRUE) ## S4 method for signature 'SpatVector,SpatExtent' erase(x, y)
x |
SpatVector |
y |
SpatVector or SpatExtent |
sequential |
logical. Should areas be erased sequentially? See Details |
If polygons are erased sequentially, everything that is covered by the first polygon is removed from all other polygons, then everything that is covered by (what is remaining of) the second polygon is removed, etc.
If polygons are not erased sequentially, all overlapping areas are erased and only the areas covered by a single geometry are returned.
SpatVector or SpatExtent
crop
and intersect
for the inverse.
The equivalent for SpatRaster is mask
f <- system.file("ex/lux.shp", package="terra") v <- vect(f) # polygons with polygons or extent e <- ext(5.6, 6, 49.55, 49.7) x <- erase(v, e) p <- vect("POLYGON ((5.8 49.8, 6 49.9, 6.15 49.8, 6 49.6, 5.8 49.8))") y <- erase(v, p) # lines with polygons lns <- as.lines(rast(v, ncol=10, nrow=10))[12:22] eln <- erase(lns, v) plot(v) lines(lns, col='blue', lwd=4, lty=3) lines(eln, col='red', lwd=2) ## self-erase h <- convHull(v[-12], "NAME_1") he <- erase(h) plot(h, lwd=2, border="red", lty=2) lines(he, col="gray", lwd=3)
f <- system.file("ex/lux.shp", package="terra") v <- vect(f) # polygons with polygons or extent e <- ext(5.6, 6, 49.55, 49.7) x <- erase(v, e) p <- vect("POLYGON ((5.8 49.8, 6 49.9, 6.15 49.8, 6 49.6, 5.8 49.8))") y <- erase(v, p) # lines with polygons lns <- as.lines(rast(v, ncol=10, nrow=10))[12:22] eln <- erase(lns, v) plot(v) lines(lns, col='blue', lwd=4, lty=3) lines(eln, col='red', lwd=2) ## self-erase h <- convHull(v[-12], "NAME_1") he <- erase(h) plot(h, lwd=2, border="red", lty=2) lines(he, col="gray", lwd=3)
Compute the area covered by polygons or for all raster cells that are not NA
.
This method computes areas for longitude/latitude rasters, as the size of the cells is constant in degrees, but not in square meters. But it can also be important if the coordinate reference system is planar, but not equal-area.
For vector data, the best way to compute area is to use the longitude/latitude CRS. This is contrary to (erroneous) popular belief that suggest that you should use a planar coordinate reference system. This is done automatically, if transform=TRUE
.
## S4 method for signature 'SpatRaster' expanse(x, unit="m", transform=TRUE, byValue=FALSE, zones=NULL, wide=FALSE, usenames=FALSE) ## S4 method for signature 'SpatVector' expanse(x, unit="m", transform=TRUE)
## S4 method for signature 'SpatRaster' expanse(x, unit="m", transform=TRUE, byValue=FALSE, zones=NULL, wide=FALSE, usenames=FALSE) ## S4 method for signature 'SpatVector' expanse(x, unit="m", transform=TRUE)
x |
SpatRaster or SpatVector |
unit |
character. Output unit of area. One of "m", "km", or "ha" |
transform |
logical. If |
byValue |
logical. If |
zones |
NULL or SpatRaster with the same geometry identifying zones in |
wide |
logical. Should the results be in "wide" rather than "long" format? |
usenames |
logical. If |
SpatRaster: data.frame
with at least two columns ("layer" and "area") and possibly also "value" (if byValue
is TRUE
), and "zone" (if zones
is TRUE
). If x
has no values, the total area of all cells is returned. Otherwise, the area of all cells that are not NA
is returned.
SpatVector: numeric (one value for each (multi-) polygon geometry.
cellSize
for a the size of individual cells of a raster, that can be summed with global
or with zonal
to get the area for different zones.
### SpatRaster r <- rast(nrows=18, ncols=36) v <- 1:ncell(r) v[200:400] <- NA values(r) <- v # summed area in km2 expanse(r, unit="km") # all cells expanse(rast(r), unit="km") r <- rast(ncols=90, nrows=45, ymin=-80, ymax=80) m <- project(r, "+proj=merc") expanse(m, unit="km") expanse(m, unit="km", transform=FALSE) m2 <- c(m, m) values(m2) <- cbind(c(1,2,NA,NA), c(11:14)) expanse(m2, unit="km", byValue=TRUE, wide=TRUE) v <- vect(system.file("ex/lux.shp", package="terra")) r <- rast(system.file("ex/elev.tif", package="terra")) r <- round((r-50)/100) levels(r) <- data.frame(id=1:5, name=c("forest", "water", "urban", "crops", "grass")) expanse(r, byValue=TRUE) g <- rasterize(v, r, "NAME_1") expanse(r, byValue=TRUE, zones=g, wide=TRUE) ### SpatVector v <- vect(system.file("ex/lux.shp", package="terra")) a <- expanse(v) a sum(a)
### SpatRaster r <- rast(nrows=18, ncols=36) v <- 1:ncell(r) v[200:400] <- NA values(r) <- v # summed area in km2 expanse(r, unit="km") # all cells expanse(rast(r), unit="km") r <- rast(ncols=90, nrows=45, ymin=-80, ymax=80) m <- project(r, "+proj=merc") expanse(m, unit="km") expanse(m, unit="km", transform=FALSE) m2 <- c(m, m) values(m2) <- cbind(c(1,2,NA,NA), c(11:14)) expanse(m2, unit="km", byValue=TRUE, wide=TRUE) v <- vect(system.file("ex/lux.shp", package="terra")) r <- rast(system.file("ex/elev.tif", package="terra")) r <- round((r-50)/100) levels(r) <- data.frame(id=1:5, name=c("forest", "water", "urban", "crops", "grass")) expanse(r, byValue=TRUE) g <- rasterize(v, r, "NAME_1") expanse(r, byValue=TRUE, zones=g, wide=TRUE) ### SpatVector v <- vect(system.file("ex/lux.shp", package="terra")) a <- expanse(v) a sum(a)
Get a SpatExtent of a SpatRaster, SpatVector, or other spatial objects. Or create a SpatExtent from a vector (length=4; order=xmin, xmax, ymin, ymax)
You can set the extent of a SpatRaster, but you cannot set the extent of a SpatVector (see rescale
for that). See set.ext
to set the extent in place.
## S4 method for signature 'SpatRaster' ext(x, cells=NULL) ## S4 method for signature 'SpatVector' ext(x) ## S4 method for signature 'numeric' ext(x, ..., xy=FALSE) ## S4 replacement method for signature 'SpatRaster,SpatExtent' ext(x)<-value ## S4 replacement method for signature 'SpatRaster,numeric' ext(x)<-value
## S4 method for signature 'SpatRaster' ext(x, cells=NULL) ## S4 method for signature 'SpatVector' ext(x) ## S4 method for signature 'numeric' ext(x, ..., xy=FALSE) ## S4 replacement method for signature 'SpatRaster,SpatExtent' ext(x)<-value ## S4 replacement method for signature 'SpatRaster,numeric' ext(x)<-value
x |
SpatRaster |
cells |
positive integer (cell) numbers to subset the extent to area covered by these cells |
value |
SpatExtent, or numeric vector of length four (xmin, xmax, ymin, ymax) |
... |
if |
xy |
logical. Set this to |
A SpatExtent
object.
r <- rast() e <- ext(r) as.vector(e) as.character(e) ext(r) <- c(0, 2.5, 0, 1.5) r er <- ext(r) round(er) # go "in" floor(er) # go "out" ceiling(er) ext(r) <- e
r <- rast() e <- ext(r) as.vector(e) as.character(e) ext(r) <- c(0, 2.5, 0, 1.5) r er <- ext(r) round(er) # go "in" floor(er) # go "out" ceiling(er) ext(r) <- e
Enlarge the spatial extent of a SpatRaster. See crop
if you (also) want to remove rows or columns.
Note that you can only enlarge SpatRasters with entire rows and columns. Therefore, the extent of the output SpatRaster may not be exactly the same as the requested. Depending on argument snap
it may be a bit smaller or larger.
You can also enlarge a SpatExtent with this method, or with an algebraic notation (see examples)
## S4 method for signature 'SpatRaster' extend(x, y, snap="near", fill=NA, filename="", overwrite=FALSE, ...) ## S4 method for signature 'SpatExtent' extend(x, y)
## S4 method for signature 'SpatRaster' extend(x, y, snap="near", fill=NA, filename="", overwrite=FALSE, ...) ## S4 method for signature 'SpatExtent' extend(x, y)
x |
SpatRaster or SpatExtent |
y |
If |
snap |
character. One of "near", "in", or "out". Used to align |
fill |
numeric. The value used to for the new raster cells |
filename |
character. Output filename |
overwrite |
logical. If |
... |
additional arguments for writing files as in |
SpatRaster or SpatExtent
r <- rast(xmin=-150, xmax=-120, ymin=30, ymax=60, ncols=36, nrows=18) values(r) <- 1:ncell(r) e <- ext(-180, -100, 40, 70) re <- extend(r, e) # extend with a number of rows and columns (at each side) re2 <- extend(r, c(2,10)) # SpatExtent e <- ext(r) e extend(e, 10) extend(e, c(10, -10, 0, 20)) # add 10 columns / rows on all sides e + 10 # double extent e * 2 # increase extent by 25% e * 1.25
r <- rast(xmin=-150, xmax=-120, ymin=30, ymax=60, ncols=36, nrows=18) values(r) <- 1:ncell(r) e <- ext(-180, -100, 40, 70) re <- extend(r, e) # extend with a number of rows and columns (at each side) re2 <- extend(r, c(2,10)) # SpatExtent e <- ext(r) e extend(e, 10) extend(e, c(10, -10, 0, 20)) # add 10 columns / rows on all sides e + 10 # double extent e * 2 # increase extent by 25% e * 1.25
Extract values from a SpatRaster for a set of locations. The locations can be a SpatVector (points, lines, polygons), a data.frame or matrix with (x, y) or (longitude, latitude – in that order!) coordinates, or a vector with cell numbers.
When argument y
is a SpatVector
the first column has the ID (record number) of the SpatVector
used (unless you set ID=FALSE
).
Alternatively, you can use zonal
after using rasterize
with a SpatVector
(this may be more efficient in some cases).
## S4 method for signature 'SpatRaster,SpatVector' extract(x, y, fun=NULL, method="simple", cells=FALSE, xy=FALSE, ID=TRUE, weights=FALSE, exact=FALSE, touches=is.lines(y), small=TRUE, layer=NULL, bind=FALSE, raw=FALSE, ...) ## S4 method for signature 'SpatRaster,SpatExtent' extract(x, y, cells=FALSE, xy=FALSE) ## S4 method for signature 'SpatRaster,matrix' extract(x, y, cells=FALSE, method="simple") ## S4 method for signature 'SpatRaster,numeric' extract(x, y, xy=FALSE, raw=FALSE) ## S4 method for signature 'SpatVector,SpatVector' extract(x, y)
## S4 method for signature 'SpatRaster,SpatVector' extract(x, y, fun=NULL, method="simple", cells=FALSE, xy=FALSE, ID=TRUE, weights=FALSE, exact=FALSE, touches=is.lines(y), small=TRUE, layer=NULL, bind=FALSE, raw=FALSE, ...) ## S4 method for signature 'SpatRaster,SpatExtent' extract(x, y, cells=FALSE, xy=FALSE) ## S4 method for signature 'SpatRaster,matrix' extract(x, y, cells=FALSE, method="simple") ## S4 method for signature 'SpatRaster,numeric' extract(x, y, xy=FALSE, raw=FALSE) ## S4 method for signature 'SpatVector,SpatVector' extract(x, y)
x |
SpatRaster or SpatVector of polygons |
y |
SpatVector (points, lines, or polygons). Alternatively, for points, a 2-column matrix or data.frame (x, y) or (lon, lat). Or a vector with cell numbers |
fun |
function to summarize the extracted data by line or polygon geometry. You can use |
method |
character. method for extracting values with points ("simple" or "bilinear"). With "simple" values for the cell a point falls in are returned. With "bilinear" the returned values are interpolated from the values of the four nearest raster cells |
cells |
logical. If |
xy |
logical. If |
ID |
logical. Should an ID column be added? If so, the first column returned has the IDs (record numbers) of |
weights |
logical. If |
exact |
logical. If |
touches |
logical. If |
small |
logical. If |
layer |
character or numeric to select the layer to extract from for each geometry. If |
bind |
logical. If |
raw |
logical. If |
... |
additional arguments to |
data.frame, matrix or SpatVector
values, zonal, extractAlong, extractRange, rapp
r <- rast(ncols=5, nrows=5, xmin=0, xmax=5, ymin=0, ymax=5) values(r) <- 1:25 xy <- rbind(c(0.5,0.5), c(2.5,2.5)) p <- vect(xy, crs="+proj=longlat +datum=WGS84") extract(r, xy) extract(r, p) r[1,] r[5] r[,5] r[c(0:2, 99:101)] f <- system.file("ex/meuse.tif", package="terra") r <- rast(f) xy <- cbind(179000, 330000) xy <- rbind(xy-100, xy, xy+1000) extract(r, xy) p <- vect(xy) g <- geom(p) g extract(r, p) x <- r + 10 extract(x, p) i <- cellFromXY(r, xy) x[i] r[i] y <- c(x,x*2,x*3) y[i] ## extract with a polygon f <- system.file("ex/lux.shp", package="terra") v <- vect(f) v <- v[1:2,] rf <- system.file("ex/elev.tif", package="terra") x <- rast(rf) extract(x, v, mean, na.rm=TRUE) z <- rast(v, resolution=.1, names="test") values(z) <- 1:ncell(z) e <- extract(z, v, ID=TRUE) e tapply(e[,2], e[,1], mean, na.rm=TRUE) x <- c(z, z*2, z/3) names(x) <- letters[1:3] e <- extract(x, v, ID=TRUE) de <- data.frame(e) aggregate(de[,2:4], de[,1,drop=FALSE], mean)
r <- rast(ncols=5, nrows=5, xmin=0, xmax=5, ymin=0, ymax=5) values(r) <- 1:25 xy <- rbind(c(0.5,0.5), c(2.5,2.5)) p <- vect(xy, crs="+proj=longlat +datum=WGS84") extract(r, xy) extract(r, p) r[1,] r[5] r[,5] r[c(0:2, 99:101)] f <- system.file("ex/meuse.tif", package="terra") r <- rast(f) xy <- cbind(179000, 330000) xy <- rbind(xy-100, xy, xy+1000) extract(r, xy) p <- vect(xy) g <- geom(p) g extract(r, p) x <- r + 10 extract(x, p) i <- cellFromXY(r, xy) x[i] r[i] y <- c(x,x*2,x*3) y[i] ## extract with a polygon f <- system.file("ex/lux.shp", package="terra") v <- vect(f) v <- v[1:2,] rf <- system.file("ex/elev.tif", package="terra") x <- rast(rf) extract(x, v, mean, na.rm=TRUE) z <- rast(v, resolution=.1, names="test") values(z) <- 1:ncell(z) e <- extract(z, v, ID=TRUE) e tapply(e[,2], e[,1], mean, na.rm=TRUE) x <- c(z, z*2, z/3) names(x) <- letters[1:3] e <- extract(x, v, ID=TRUE) de <- data.frame(e) aggregate(de[,2:4], de[,1,drop=FALSE], mean)
Extract raster values along a line. That is, the returned values are ordered along the line. That is not the case with extract
extractAlong(x, y, ID=TRUE, cells=FALSE, xy=FALSE, online=FALSE, bilinear=TRUE)
extractAlong(x, y, ID=TRUE, cells=FALSE, xy=FALSE, online=FALSE, bilinear=TRUE)
x |
SpatRaster |
y |
SpatVector with lines geometry |
ID |
logical. Should an ID column be added? If so, the first column returned has the IDs (record numbers) of input SpatVector |
cells |
logical. If |
xy |
logical. If |
online |
logical. If |
bilinear |
logical. If |
data.frame
r <- rast(ncols=36, nrows=18, vals=1:(18*36)) cds1 <- rbind(c(-50,0), c(0,60), c(40,5), c(15,-45), c(-10,-25)) cds2 <- rbind(c(80,20), c(140,60), c(160,0), c(140,-55)) lines <- vect(list(cds1, cds2), "lines") extractAlong(r, lines)
r <- rast(ncols=36, nrows=18, vals=1:(18*36)) cds1 <- rbind(c(-50,0), c(0,60), c(40,5), c(15,-45), c(-10,-25)) cds2 <- rbind(c(80,20), c(140,60), c(160,0), c(140,-55)) lines <- vect(list(cds1, cds2), "lines") extractAlong(r, lines)
Extract values from a SpatRaster for a set of locations and a range of layers. To extract values for a single or all layers, use extract
## S4 method for signature 'SpatRaster' extractRange(x, y, first, last, lyr_fun=NULL, geom_fun=NULL, ID=FALSE, na.rm=TRUE, ...)
## S4 method for signature 'SpatRaster' extractRange(x, y, first, last, lyr_fun=NULL, geom_fun=NULL, ID=FALSE, na.rm=TRUE, ...)
x |
SpatRaster |
y |
SpatVector (points, lines, or polygons). Alternatively, for points, a 2-column matrix or data.frame (x, y) or (lon, lat). Or a vector with cell numbers |
first |
layer name of number, indicating the first layer in the range of layers to be considered |
last |
layer name or number, indicating the last layer in the range to be considered |
lyr_fun |
function to summarize the extracted data across layers |
geom_fun |
function to summarize the extracted data for each line or polygon geometry. Ignored if |
ID |
logical. Should an ID column be added? If so, the first column returned has the IDs (record numbers) of |
na.rm |
logical. Should missing values be ignored? |
... |
additional arguments passed to |
numeric or data.frame
r <- rast(system.file("ex/logo.tif", package="terra")) xy <- data.frame(c(50,80), c(30, 60)) extract(r, xy) extract(r, xy, layer=c("red", "green")) extractRange(r, xy, first=1:2, last=3:2, lyr_fun=sum)
r <- rast(system.file("ex/logo.tif", package="terra")) xy <- data.frame(c(50,80), c(30, 60)) extract(r, xy) extract(r, xy, layer=c("red", "green")) extractRange(r, xy, first=1:2, last=3:2, lyr_fun=sum)
The minimum and maximum value of a SpatRaster are returned or computed (from a file on disk if necessary) and stored in the object.
## S4 method for signature 'SpatRaster' minmax(x, compute=FALSE) ## S4 method for signature 'SpatRaster' hasMinMax(x) ## S4 method for signature 'SpatRaster' setMinMax(x, force=FALSE)
## S4 method for signature 'SpatRaster' minmax(x, compute=FALSE) ## S4 method for signature 'SpatRaster' hasMinMax(x) ## S4 method for signature 'SpatRaster' setMinMax(x, force=FALSE)
x |
SpatRaster |
compute |
logical. If |
force |
logical. If |
minmax: numeric matrix of minimum and maximum cell values by layer
hasMinMax: logical indicating whether the min and max values are available.
setMinMax: nothing. Used for the side-effect of computing the minimum and maximum values of a SpatRaster
r <- rast(system.file("ex/elev.tif", package="terra")) minmax(r)
r <- rast(system.file("ex/elev.tif", package="terra")) minmax(r)
A SpatRaster layer can represent a categorical variable (factor). Like factor
s, SpatRaster categories are stored as integers that have an associated label.
The categories can be inspected with levels
and cats
. They are represented by a data.frame
that must have two or more columns, the first one identifying the (integer) cell values and the other column(s) providing the category labels.
If there are multiple columns with categories, you can set the "active" category to choose the one you want to use.
cats
returns the entire data.frame, whereas levels
only return two columns: the index and the active category.
To set categories for the first layer of a SpatRaster, you can provide levels<-
with a data.frame or a list with a data.frame. To set categories for multiple layers you can provide levels<-
with a list with one element (that either has a data.frame
or is NULL
) for each layer. Use categories
to set the categories for a specific layer or specific layers.
droplevels
removes categories that are not used (declared but not present as values in the raster) if levels=NULL
.
addCats
adds additional categories to a layer that already is categorical. It adds new variables, not new levels of an existing categorical variable.
## S4 method for signature 'SpatRaster' levels(x) ## S4 replacement method for signature 'SpatRaster' levels(x)<-value ## S4 method for signature 'SpatRaster' cats(x, layer) ## S4 method for signature 'SpatRaster' categories(x, layer=1, value, active=1, ...) ## S4 method for signature 'SpatRaster' droplevels(x, level=NULL, layer=1) ## S4 method for signature 'SpatRaster' addCats(x, value, merge=FALSE, layer=1)
## S4 method for signature 'SpatRaster' levels(x) ## S4 replacement method for signature 'SpatRaster' levels(x)<-value ## S4 method for signature 'SpatRaster' cats(x, layer) ## S4 method for signature 'SpatRaster' categories(x, layer=1, value, active=1, ...) ## S4 method for signature 'SpatRaster' droplevels(x, level=NULL, layer=1) ## S4 method for signature 'SpatRaster' addCats(x, value, merge=FALSE, layer=1)
x |
SpatRaster |
layer |
the layer name or number (positive integer); or 0 for all layers |
value |
a data.frame (ID, category) that define the categories. Or |
active |
positive integer, indicating the column in |
level |
the categories to remove for the layer specified with |
merge |
logical. If |
... |
additional arguments (none) |
list of data.frames (levels, cats) or logical (is.factor)
activeCat
, catalyze
, set.cats
, as.factor
, is.factor
set.seed(0) r <- rast(nrows=10, ncols=10) values(r) <- sample(3, ncell(r), replace=TRUE) is.factor(r) cls <- data.frame(id=1:3, cover=c("forest", "water", "urban")) levels(r) <- cls is.factor(r) r plot(r, col=c("green", "blue", "light gray")) text(r, digits=3, cex=.75, halo=TRUE) # raster starts at 3 x <- r + 2 is.factor(x) # Multiple categories d <- data.frame(id=3:5, cover=cls[,2], letters=letters[1:3], value=10:12) levels(x) <- d x # get current index activeCat(x) # set index activeCat(x) <- 3 activeCat(x) activeCat(x) <- "letters" plot(x, col=c("green", "blue", "light gray")) text(x, digits=3, cex=.75, halo=TRUE) r <- as.numeric(x) r p <- as.polygons(x) plot(p, "letters", col=c("green", "blue", "light gray"))
set.seed(0) r <- rast(nrows=10, ncols=10) values(r) <- sample(3, ncell(r), replace=TRUE) is.factor(r) cls <- data.frame(id=1:3, cover=c("forest", "water", "urban")) levels(r) <- cls is.factor(r) r plot(r, col=c("green", "blue", "light gray")) text(r, digits=3, cex=.75, halo=TRUE) # raster starts at 3 x <- r + 2 is.factor(x) # Multiple categories d <- data.frame(id=3:5, cover=cls[,2], letters=letters[1:3], value=10:12) levels(x) <- d x # get current index activeCat(x) # set index activeCat(x) <- 3 activeCat(x) activeCat(x) <- "letters" plot(x, col=c("green", "blue", "light gray")) text(x, digits=3, cex=.75, halo=TRUE) r <- as.numeric(x) r p <- as.polygons(x) plot(p, "letters", col=c("green", "blue", "light gray"))
Remove the holes in SpatVector polygons. If inverse=TRUE
the holes are returned (as polygons).
## S4 method for signature 'SpatVector' fillHoles(x, inverse=FALSE)
## S4 method for signature 'SpatVector' fillHoles(x, inverse=FALSE)
x |
SpatVector |
inverse |
logical. If |
SpatVector
x <- rbind(c(-10,0), c(140,60), c(160,0), c(140,-55)) hole <- rbind(c(80,0), c(105,13), c(120,2), c(105,-13)) z <- rbind(cbind(object=1, part=1, x, hole=0), cbind(object=1, part=1, hole, hole=1)) colnames(z)[3:4] <- c('x', 'y') p <- vect(z, "polygons", atts=data.frame(id=1)) p f <- fillHoles(p) g <- fillHoles(p, inverse=TRUE) plot(p, lwd=16, border="gray", col="light yellow") polys(f, border="blue", lwd=3, density=4, col="orange") polys(g, col="white", lwd=3)
x <- rbind(c(-10,0), c(140,60), c(160,0), c(140,-55)) hole <- rbind(c(80,0), c(105,13), c(120,2), c(105,-13)) z <- rbind(cbind(object=1, part=1, x, hole=0), cbind(object=1, part=1, hole, hole=1)) colnames(z)[3:4] <- c('x', 'y') p <- vect(z, "polygons", atts=data.frame(id=1)) p f <- fillHoles(p) g <- fillHoles(p, inverse=TRUE) plot(p, lwd=16, border="gray", col="light yellow") polys(f, border="blue", lwd=3, density=4, col="orange") polys(g, col="white", lwd=3)
Add empty layers in between existing layers such that the time step between each layer is the same.
See approximate
to estimate values for these layer (and other missing values)
## S4 method for signature 'SpatRaster' fillTime(x, filename="", ...)
## S4 method for signature 'SpatRaster' fillTime(x, filename="", ...)
x |
SpatRaster |
filename |
character. Output filename |
... |
list with named options for writing files as in |
SpatRaster
r <- rast(system.file("ex/logo.tif", package="terra")) s <- c(r, r) time(s) <- as.Date("2001-01-01") + c(0:2, 5:7) time(s) ss <- fillTime(s) time(ss) a <- approximate(ss)
r <- rast(system.file("ex/logo.tif", package="terra")) s <- c(r, r) time(s) <- as.Date("2001-01-01") + c(0:2, 5:7) time(s) ss <- fillTime(s) time(ss) a <- approximate(ss)
Flip the values of a SpatRaster by inverting the order of the rows (vertical=TRUE
) or the columns (vertical=FALSE
).
rev
is the same as a horizontal *and* a vertical flip.
## S4 method for signature 'SpatRaster' flip(x, direction="vertical", filename="", ...) ## S4 method for signature 'SpatVector' flip(x, direction="vertical") ## S4 method for signature 'SpatRaster' rev(x)
## S4 method for signature 'SpatRaster' flip(x, direction="vertical", filename="", ...) ## S4 method for signature 'SpatVector' flip(x, direction="vertical") ## S4 method for signature 'SpatRaster' rev(x)
x |
SpatRaster or SpatVector |
direction |
character. Should (partially) match "vertical" to flip by rows, or "horizontal" to flip by columns |
filename |
character. Output filename |
... |
additional arguments for writing files as in |
SpatRaster
r <- rast(nrow=18, ncol=36) m <- matrix(1:ncell(r), nrow=18) values(r) <- as.vector(t(m)) rx <- flip(r, direction="h") values(r) <- as.vector(m) ry <- flip(r, direction="v") v <- rev(r)
r <- rast(nrow=18, ncol=36) m <- matrix(1:ncell(r), nrow=18) values(r) <- as.vector(t(m)) rx <- flip(r, direction="h") values(r) <- as.vector(m) ry <- flip(r, direction="v") v <- rev(r)
Computes flow accumulation or the total contributing area in terms of numbers of cells upstream of each cell.
## S4 method for signature 'SpatRaster' flowAccumulation(x, weight=NULL, filename="", ...)
## S4 method for signature 'SpatRaster' flowAccumulation(x, weight=NULL, filename="", ...)
x |
SpatRaster with flow direction, see |
weight |
SpatRaster with weight/score daa. For example, cell area or precipitation |
filename |
character. Output filename |
... |
additional arguments for writing files as in |
The algorithm is an adaptation of the one proposed by Zhou at al, 2019.
SpatRaster
Emanuele Cordano
Zhou, G., Wei, H. & Fu, S. A fast and simple algorithm for calculating flow accumulation matrices from raster digital elevation. Front. Earth Sci. 13, 317–326 (2019). doi:10.1007/s11707-018-0725-9. Also see: https://ica-abs.copernicus.org/articles/1/434/2019/
elev1 <- array(NA,c(9,9)) elev2 <- elev1 dx <- 1 dy <- 1 for (r in 1:nrow(elev1)) { y <- (r-5)*dx for (c in 1:ncol(elev1)) { x <- (c-5)*dy elev1[r,c] <- 5*(x^2+y^2) elev2[r,c] <- 10+5*(abs(x))-0.001*y } } ## Elevation raster elev1 <- rast(elev1) elev2 <- rast(elev2) t(array(elev1[],rev(dim(elev1)[1:2]))) t(array(elev2[],rev(dim(elev2)[1:2]))) plot(elev1) plot(elev2) ## Flow direction raster flowdir1<- terrain(elev1,v="flowdir") flowdir2<- terrain(elev2,v="flowdir") t(array(flowdir1[],rev(dim(flowdir1)[1:2]))) t(array(flowdir2[],rev(dim(flowdir2)[1:2]))) plot(flowdir1) plot(flowdir2) ## flow_acc1 <- flowAccumulation((flowdir1)) flow_acc2 <- flowAccumulation((flowdir2)) weight <- elev1*0+10 flow_acc1w <- flowAccumulation(flowdir1,weight) flow_acc2w <- flowAccumulation(flowdir2,weight) t(array(flow_acc1w[],rev(dim(flow_acc1w)[1:2]))) t(array(flow_acc2w[],rev(dim(flow_acc2w)[1:2]))) plot(flow_acc1w) plot(flow_acc2w) ## Application wth example elevation data elev <- rast(system.file('ex/elev.tif',package="terra")) flowdir <- terrain(elev,"flowdir") weight <- cellSize(elev,unit="km") flowacc_weight <- flowAccumulation(flowdir,weight) flowacc <- flowAccumulation(flowdir)
elev1 <- array(NA,c(9,9)) elev2 <- elev1 dx <- 1 dy <- 1 for (r in 1:nrow(elev1)) { y <- (r-5)*dx for (c in 1:ncol(elev1)) { x <- (c-5)*dy elev1[r,c] <- 5*(x^2+y^2) elev2[r,c] <- 10+5*(abs(x))-0.001*y } } ## Elevation raster elev1 <- rast(elev1) elev2 <- rast(elev2) t(array(elev1[],rev(dim(elev1)[1:2]))) t(array(elev2[],rev(dim(elev2)[1:2]))) plot(elev1) plot(elev2) ## Flow direction raster flowdir1<- terrain(elev1,v="flowdir") flowdir2<- terrain(elev2,v="flowdir") t(array(flowdir1[],rev(dim(flowdir1)[1:2]))) t(array(flowdir2[],rev(dim(flowdir2)[1:2]))) plot(flowdir1) plot(flowdir2) ## flow_acc1 <- flowAccumulation((flowdir1)) flow_acc2 <- flowAccumulation((flowdir2)) weight <- elev1*0+10 flow_acc1w <- flowAccumulation(flowdir1,weight) flow_acc2w <- flowAccumulation(flowdir2,weight) t(array(flow_acc1w[],rev(dim(flow_acc1w)[1:2]))) t(array(flow_acc2w[],rev(dim(flow_acc2w)[1:2]))) plot(flow_acc1w) plot(flow_acc2w) ## Application wth example elevation data elev <- rast(system.file('ex/elev.tif',package="terra")) flowdir <- terrain(elev,"flowdir") weight <- cellSize(elev,unit="km") flowacc_weight <- flowAccumulation(flowdir,weight) flowacc <- flowAccumulation(flowdir)
Calculate focal ("moving window") values for each cell.
## S4 method for signature 'SpatRaster' focal(x, w=3, fun="sum", ..., na.policy="all", fillvalue=NA, expand=FALSE, silent=TRUE, filename="", overwrite=FALSE, wopt=list())
## S4 method for signature 'SpatRaster' focal(x, w=3, fun="sum", ..., na.policy="all", fillvalue=NA, expand=FALSE, silent=TRUE, filename="", overwrite=FALSE, wopt=list())
x |
SpatRaster |
w |
window. The window can be defined as one (for a square) or two numbers (row, col); or with an odd-sized weights matrix. See Details. |
fun |
function that takes multiple numbers, and returns a numeric vector (one or multiple numbers). For example mean, modal, min or max |
... |
additional arguments passed to |
na.policy |
character. Can be used to determine the cells of |
fillvalue |
numeric. The value of the cells in the virtual rows and columns outside of the raster |
expand |
logical. If |
silent |
logical. If |
filename |
character. Output filename |
overwrite |
logical. If |
wopt |
additional arguments for writing files as in |
focal
The window used must have odd dimensions. If you need even sides, you can use a matrix and add a column or row of NA
's to mask out values.
Window values are typically 1 or NA
to indicate whether a value is used or ignored in computations, respectively. NA
values in w
can be useful for creating non-rectangular (e.g. circular) windows.
A weights matrix of numeric values can also be supplied to w
. In the case of a weights matrix, cells with NA
weights will be ignored, and the rest of the values in the focal window will be multiplied by the corresponding weight prior to 'fun' being applied. Note, na.rm
does not need to be TRUE
if w
contains NA
values as these cells are ignored in computations.
The "mean" function is a special case, where supplying weights to w
will instead calculate a weighted mean.
The "sum" function returns NA
if all focal cells are NA
and na.rm=TRUE
. R would normally return a zero in these cases. See the difference between focal(x, fun=sum, na.rm=TRUE)
and focal(x, fun=\(i) sum(i, na.rm=TRUE))
Example weight matrices
Laplacian filter: filter=matrix(c(0,1,0,1,-4,1,0,1,0), nrow=3)
Sobel filters (for edge detection):
fx=matrix(c(-1,-2,-1,0,0,0,1,2,1), nrow=3)
fy=matrix(c(1,0,-1,2,0,-2,1,0,-1), nrow=3)
SpatRaster
When using global lon/lat rasters, the focal window "wraps around" the date-line.
focalMat
, focalValues
, focal3D
, focalPairs
, focalReg
, focalCpp
r <- rast(ncols=10, nrows=10, ext(0, 10, 0, 10)) values(r) <- 1:ncell(r) f <- focal(r, w=3, fun=function(x, ...) quantile(x, c(.25, .5, .75), ...), na.rm=TRUE) f <- focal(r, w=3, fun="mean") # the following two statements are equivalent: a <- focal(r, w=matrix(1/9, nc=3, nr=3)) b <- focal(r, w=3, fun=mean, na.rm=FALSE) # but this is different d <- focal(r, w=3, fun=mean, na.rm=TRUE) ## illustrating the effect of different ## combinations of na.rm and na.policy v <- vect(system.file("ex/lux.shp", package="terra")) r <- rast(system.file("ex/elev.tif", package="terra")) r[45:50, 45:50] <- NA # also try "mean" or "min" f <- "sum" # na.rm=FALSE plot(focal(r, 5, f) , fun=lines(v)) # na.rm=TRUE plot(focal(r, 5, f, na.rm=TRUE), fun=lines(v)) # only change cells that are NA plot(focal(r, 5, f, na.policy="only", na.rm=TRUE), fun=lines(v)) # do not change cells that are NA plot(focal(r, 5, f, na.policy="omit", na.rm=TRUE), fun=lines(v)) # does not do anything # focal(r, 5, f, na.policy="only", na.rm=FALSE)
r <- rast(ncols=10, nrows=10, ext(0, 10, 0, 10)) values(r) <- 1:ncell(r) f <- focal(r, w=3, fun=function(x, ...) quantile(x, c(.25, .5, .75), ...), na.rm=TRUE) f <- focal(r, w=3, fun="mean") # the following two statements are equivalent: a <- focal(r, w=matrix(1/9, nc=3, nr=3)) b <- focal(r, w=3, fun=mean, na.rm=FALSE) # but this is different d <- focal(r, w=3, fun=mean, na.rm=TRUE) ## illustrating the effect of different ## combinations of na.rm and na.policy v <- vect(system.file("ex/lux.shp", package="terra")) r <- rast(system.file("ex/elev.tif", package="terra")) r[45:50, 45:50] <- NA # also try "mean" or "min" f <- "sum" # na.rm=FALSE plot(focal(r, 5, f) , fun=lines(v)) # na.rm=TRUE plot(focal(r, 5, f, na.rm=TRUE), fun=lines(v)) # only change cells that are NA plot(focal(r, 5, f, na.policy="only", na.rm=TRUE), fun=lines(v)) # do not change cells that are NA plot(focal(r, 5, f, na.policy="omit", na.rm=TRUE), fun=lines(v)) # does not do anything # focal(r, 5, f, na.policy="only", na.rm=FALSE)
Calculate focal ("moving window") values for the three-dimensional neighborhood (window) of focal cells. See focal
for two-dimensional focal computation.
## S4 method for signature 'SpatRaster' focal3D(x, w=3, fun=mean, ..., na.policy="all", fillvalue=NA, pad=FALSE, padvalue=fillvalue, expand=FALSE, silent=TRUE, filename="", overwrite=FALSE, wopt=list())
## S4 method for signature 'SpatRaster' focal3D(x, w=3, fun=mean, ..., na.policy="all", fillvalue=NA, pad=FALSE, padvalue=fillvalue, expand=FALSE, silent=TRUE, filename="", overwrite=FALSE, wopt=list())
x |
SpatRaster |
w |
window. A rectangular prism (cuboid) defined by three numbers or by a three-dimensional array. The values are used as weights, and are usually zero, one, NA, or fractions. The window used must have odd dimensions. If you desire to use even sides, you can use an array, and pad the values with rows and/or columns that contain only |
fun |
function that takes multiple numbers, and returns one or multiple numbers for each focal area. For example mean, modal, min or max |
... |
additional arguments passed to |
na.policy |
character. Can be used to determine the cells of |
fillvalue |
numeric. The value of the cells in the virtual rows and columns outside of the raster |
pad |
logical. Add virtual layers before the first and after the last layer |
padvalue |
numeric. The value of the cells in the virtual layers |
expand |
logical. Add virtual layers before the first or after the last layer that are the same as the first or last layers. If |
silent |
logical. If |
filename |
character. Output filename |
overwrite |
logical. If |
wopt |
additional arguments for writing files as in |
SpatRaster
r <- rast(system.file("ex/logo.tif", package="terra")) x <- focal3D(r, c(5,5,3), na.rm=TRUE) a <- array(c(0,1,0,1,1,1,0,1,0, rep(1,9), 0,1,0,1,1,1,0,1,0), c(3,3,3)) a[a==0] <- NA z <- focal3D(r, a, na.rm=TRUE)
r <- rast(system.file("ex/logo.tif", package="terra")) x <- focal3D(r, c(5,5,3), na.rm=TRUE) a <- array(c(0,1,0,1,1,1,0,1,0, rep(1,9), 0,1,0,1,1,1,0,1,0), c(3,3,3)) a[a==0] <- NA z <- focal3D(r, a, na.rm=TRUE)
Calculate focal values with a C++ function that iterates over cells to speed up computations by avoiding an R loop (with apply).
See focal
for an easier to use method.
## S4 method for signature 'SpatRaster' focalCpp(x, w=3, fun, ..., fillvalue=NA, silent=TRUE, filename="", overwrite=FALSE, wopt=list())
## S4 method for signature 'SpatRaster' focalCpp(x, w=3, fun, ..., fillvalue=NA, silent=TRUE, filename="", overwrite=FALSE, wopt=list())
x |
SpatRaster |
w |
window. The window can be defined as one (for a square) or two numbers (row, col); or with an odd-sized weights matrix. See the Details section in |
fun |
|
... |
additional arguments to |
fillvalue |
numeric. The value of the cells in the virtual rows and columns outside of the raster |
silent |
logical. If |
filename |
character. Output filename |
overwrite |
logical. If |
wopt |
additional arguments for writing files as in |
SpatRaster
## Not run: library(Rcpp) cppFunction( 'NumericVector sum_and_multiply(NumericVector x, double m, size_t ni, size_t nw) { NumericVector out(ni); // loop over cells size_t start = 0; for (size_t i=0; i<ni; i++) { size_t end = start + nw; // compute something for a window double v = 0; // loop over the values of a window for (size_t j=start; j<end; j++) { v += x[j]; } out[i] = v * m; start = end; } return out; }' ) nr <- nc <- 10 r <- rast(ncols=nc, nrows=nr, ext= c(0, nc, 0, nr)) values(r) <- 1:ncell(r) raw <- focalCpp(r, w=3, fun=sum_and_multiply, fillvalue=0, m=10) # same as f1 <- focal(r, w=3, fun=sum, fillvalue=0) *10 all(values(f1) == values(raw)) # and as ffun <- function(x, m) { sum(x) * m } f2 <- focal(r, w=3, fun=ffun, fillvalue=0, m=10) # You can also use an R function with focalCpp but this # is not recommended R_sm_iter <- function(x, m, ni, nw) { out <- NULL for (i in 1:ni) { start <- (i-1) * nw + 1 out[i] <- sum(x[start:(start+nw-1)]) * m } out } fr <- focalCpp(r, w=3, fun=R_sm_iter, fillvalue=0, m=10) ## End(Not run)
## Not run: library(Rcpp) cppFunction( 'NumericVector sum_and_multiply(NumericVector x, double m, size_t ni, size_t nw) { NumericVector out(ni); // loop over cells size_t start = 0; for (size_t i=0; i<ni; i++) { size_t end = start + nw; // compute something for a window double v = 0; // loop over the values of a window for (size_t j=start; j<end; j++) { v += x[j]; } out[i] = v * m; start = end; } return out; }' ) nr <- nc <- 10 r <- rast(ncols=nc, nrows=nr, ext= c(0, nc, 0, nr)) values(r) <- 1:ncell(r) raw <- focalCpp(r, w=3, fun=sum_and_multiply, fillvalue=0, m=10) # same as f1 <- focal(r, w=3, fun=sum, fillvalue=0) *10 all(values(f1) == values(raw)) # and as ffun <- function(x, m) { sum(x) * m } f2 <- focal(r, w=3, fun=ffun, fillvalue=0, m=10) # You can also use an R function with focalCpp but this # is not recommended R_sm_iter <- function(x, m, ni, nw) { out <- NULL for (i in 1:ni) { start <- (i-1) * nw + 1 out[i] <- sum(x[start:(start+nw-1)]) * m } out } fr <- focalCpp(r, w=3, fun=R_sm_iter, fillvalue=0, m=10) ## End(Not run)
Make a focal ("moving window") weight matrix for use in the focal
function. The sum of the values adds up to one.
focalMat(x, d, type=c('circle', 'Gauss', 'rectangle'), fillNA=FALSE)
focalMat(x, d, type=c('circle', 'Gauss', 'rectangle'), fillNA=FALSE)
x |
SpatRaster |
d |
numeric. If |
type |
character indicating the type of filter to be returned |
fillNA |
logical. If |
matrix that can be used with focal
r <- rast(ncols=180, nrows=180, xmin=0) focalMat(r, 2, "circle") focalMat(r, c(2,3), "rect") # Gaussian filter for square cells gf <- focalMat(r, 1, "Gauss")
r <- rast(ncols=180, nrows=180, xmin=0) focalMat(r, 2, "circle") focalMat(r, c(2,3), "rect") # Gaussian filter for square cells gf <- focalMat(r, 1, "Gauss")
Calculate values such as a correlation coefficient for focal regions in two neighboring layers. A function is applied to the first and second layer, then to the second and third layer, etc.
## S4 method for signature 'SpatRaster' focalPairs(x, w=3, fun, ..., fillvalue=NA, filename="", overwrite=FALSE, wopt=list())
## S4 method for signature 'SpatRaster' focalPairs(x, w=3, fun, ..., fillvalue=NA, filename="", overwrite=FALSE, wopt=list())
x |
SpatRaster with at least two layers |
w |
numeric or matrix to define the focal window. The window an be defined as one (for a square) or two numbers (row, col); or with an odd-sized weights matrix. See the Details section in |
fun |
a function with at least two arguments (one for each layer). There is a built-in function "pearson" (for both the weighted and the unweighted Pearson correlation coefficient. This function has an additional argument |
... |
additional arguments for |
fillvalue |
numeric. The value of the cells in the virtual rows and columns outside of the raster |
filename |
character. Output filename |
overwrite |
logical. If |
wopt |
additional arguments for writing files as in |
SpatRaster
layerCor
, focalReg
, focal
, focal3D
r <- rast(system.file("ex/logo.tif", package="terra")) set.seed(0) r[[1]] <- flip(r[[1]], "horizontal") r[[2]] <- flip(r[[2]], "vertical") + init(rast(r,1), runif) r[[3]] <- init(rast(r,1), runif) x <- focalPairs(r, w=5, "pearson", na.rm=TRUE) plot(x) # suppress warning "the standard deviation is zero" suppressWarnings(x <- focalPairs(r, w=5, "pearson", use="complete.obs")) z <- focalPairs(r, w=9, function(x, y) mean(x) + mean(y))
r <- rast(system.file("ex/logo.tif", package="terra")) set.seed(0) r[[1]] <- flip(r[[1]], "horizontal") r[[2]] <- flip(r[[2]], "vertical") + init(rast(r,1), runif) r[[3]] <- init(rast(r,1), runif) x <- focalPairs(r, w=5, "pearson", na.rm=TRUE) plot(x) # suppress warning "the standard deviation is zero" suppressWarnings(x <- focalPairs(r, w=5, "pearson", use="complete.obs")) z <- focalPairs(r, w=9, function(x, y) mean(x) + mean(y))
Calculate values for a moving-window by comparing the value in one layers with the values in one to many other layers. A typical case is the computation of the coefficients for a focal linear regression model.
## S4 method for signature 'SpatRaster' focalReg(x, w=3, fun="ols", ..., fillvalue=NA, filename="", overwrite=FALSE, wopt=list())
## S4 method for signature 'SpatRaster' focalReg(x, w=3, fun="ols", ..., fillvalue=NA, filename="", overwrite=FALSE, wopt=list())
x |
SpatRaster with at least two layers. The first is the "Y" (dependent) variable and the remainder are the "X" (independent) variables |
w |
numeric or matrix to define the focal window. The window an be defined as one (for a square) or two numbers (row, col); or with an odd-sized weights matrix. See the Details section in |
fun |
a function with at least two arguments (one for each layer). There is a built-in function "ols" for both the weighted and unweighted Ordinary Least Square regression. This function has an additional argument |
... |
additional arguments for |
fillvalue |
numeric. The value of the cells in the virtual rows and columns outside of the raster |
filename |
character. Output filename |
overwrite |
logical. If |
wopt |
additional arguments for writing files as in |
SpatRaster
r <- rast(ncols=10, nrows=10, ext(0, 10, 0, 10)) values(r) <- 1:ncell(r) x <- c(r, init(r, runif) * r) f <- focalReg(x, 3)
r <- rast(ncols=10, nrows=10, ext(0, 10, 0, 10)) values(r) <- 1:ncell(r) x <- c(r, init(r, runif) * r) f <- focalReg(x, 3)
Get a matrix in which each row had the focal values of a cell. These are the values of a cell and a rectangular window around it.
## S4 method for signature 'SpatRaster' focalValues(x, w=3, row=1, nrows=nrow(x), fill=NA)
## S4 method for signature 'SpatRaster' focalValues(x, w=3, row=1, nrows=nrow(x), fill=NA)
x |
SpatRaster or SpatVector |
w |
window. The window can be defined as one (for a square) or two odd numbers (row, col); or with an odd sized matrix |
row |
positive integer. Row number to start from, should be between 1 and nrow(x) |
nrows |
positive integer. How many rows? |
fill |
numeric used as values for imaginary cells outside the raster |
matrix
r <- rast(ncol=4, nrow=4, crs="+proj=utm +zone=1 +datum=WGS84") values(r) <- 1:ncell(r) focalValues(r)
r <- rast(ncol=4, nrow=4, crs="+proj=utm +zone=1 +datum=WGS84") values(r) <- 1:ncell(r) focalValues(r)
Assure that the nodes of outer rings of polygons are in counter-clockwise order.
## S4 method for signature 'SpatVector' forceCCW(x)
## S4 method for signature 'SpatVector' forceCCW(x)
x |
SpatVector of polygons |
SpatVector
p <- vect("POLYGON ((2 45, 2 55, 18 55, 18 45, 2 45))") pcc <- forceCCW(p) geom(pcc, wkt=TRUE)
p <- vect("POLYGON ((2 45, 2 55, 18 55, 18 45, 2 45))") pcc <- forceCCW(p) geom(pcc, wkt=TRUE)
Frequency table of the values of a SpatRaster. NA
s are not counted unless value=NA
.
You can provide a SpatVector or additional SpatRaster to define zones for which to do tabulations.
## S4 method for signature 'SpatRaster' freq(x, digits=0, value=NULL, bylayer=TRUE, usenames=FALSE, zones=NULL, wide=FALSE)
## S4 method for signature 'SpatRaster' freq(x, digits=0, value=NULL, bylayer=TRUE, usenames=FALSE, zones=NULL, wide=FALSE)
x |
SpatRaster |
digits |
integer. Used for rounding the values before tabulation. Ignored if |
value |
numeric. An optional single value to only count the number of cells with that value. This value can be |
bylayer |
logical. If |
usenames |
logical. If |
zones |
SpatRaster or SpatVector to define zones for which the tabulation should be done |
wide |
logical. Should the results by "wide" instead of "long"? |
A data.frame
with 3 columns (layer, value, count) unless bylayer=FALSE
in which case adata.frame
with two columns is returned (value, count).
r <- rast(nrows=10, ncols=10) set.seed(2) values(r) <- sample(5, ncell(r), replace=TRUE) freq(r) x <- c(r, r/3) freq(x, bylayer=FALSE) freq(x) freq(x, digits=1) freq(x, digits=-1) freq(x, value=5)
r <- rast(nrows=10, ncols=10) set.seed(2) values(r) <- sample(5, ncell(r), replace=TRUE) freq(r) x <- c(r, r/3) freq(x, bylayer=FALSE) freq(x) freq(x, digits=1) freq(x, digits=-1) freq(x, value=5)
Get the gaps between polygons of a SpatVector
## S4 method for signature 'SpatVector' gaps(x)
## S4 method for signature 'SpatVector' gaps(x)
x |
SpatVector |
SpatVector
sharedPaths
, topology
, and
fillHoles
to get or remove polygon holes
f <- system.file("ex/lux.shp", package="terra") v <- vect(f) h <- convHull(v[-12], "NAME_1") g <- gaps(h)
f <- system.file("ex/lux.shp", package="terra") v <- vect(f) h <- convHull(v[-12], "NAME_1") g <- gaps(h)
Set the GDAL
warning level or get a data.frame
with the available GDAL drivers (file formats), or, if warn=NA
and drivers=FALSE
, you get the version numbers of one or all of the GDAL, PROJ and GEOS libraries.
GDAL
is the software library that terra builds on to read and write spatial data and for some raster data processing. PROJ
is used for transformation of coordinates ("projection") and GEOS
is used for geometric operations with vector data.
gdal(warn=NA, drivers=FALSE, lib="gdal") gdalCache(size=NA) setGDALconfig(option, value="") getGDALconfig(option)
gdal(warn=NA, drivers=FALSE, lib="gdal") gdalCache(size=NA) setGDALconfig(option, value="") getGDALconfig(option)
warn |
If |
drivers |
logical. If |
lib |
character. "gdal", "proj", or "geos", or any other value to get the versions numbers of all three |
size |
numeric. The new cache size in MB |
option |
character. GDAL configuration option name, or a "name=value" string (in which case the value argument is ignored |
value |
character. value for GDAL configuration option. Use "" to reset it to its default value |
character
describe
for file-level metadata "GDALinfo"
gdal() gdal(2) head(gdal(drivers=TRUE))
gdal() gdal(2) head(gdal(drivers=TRUE))
Get the geometry of a SpatVector. If wkt=FALSE
, this is a five-column matrix or data.frame: the vector object ID, the IDs for the parts of each object (e.g. five polygons that together are one spatial object), the x (longitude) and y (latitude) coordinates, and a flag indicating whether the part is a "hole" (only relevant for polygons).
If wkt=TRUE
, the "well-known text" representation is returned as a character vector.
If hex=TRUE
, the "hexademical" representation is returned as a character vector.
If wkb=TRUE
, the "well-known binary" representation is returned as a list of raw vectors.
## S4 method for signature 'SpatVector' geom(x, wkt=FALSE, hex=FALSE, wkb=FALSE, df=FALSE, list=FALSE, xnm="x", ynm="y")
## S4 method for signature 'SpatVector' geom(x, wkt=FALSE, hex=FALSE, wkb=FALSE, df=FALSE, list=FALSE, xnm="x", ynm="y")
x |
SpatVector |
wkt |
logical. If |
hex |
logical. If |
wkb |
logical. If |
df |
logical. If |
list |
logical. If |
xnm |
character. If |
ynm |
character. If |
matrix, vector, data.frame, or list
x1 <- rbind(c(-175,-20), c(-140,55), c(10, 0), c(-140,-60)) x2 <- rbind(c(-125,0), c(0,60), c(40,5), c(15,-45)) x3 <- rbind(c(-10,0), c(140,60), c(160,0), c(140,-55)) x4 <- rbind(c(80,0), c(105,13), c(120,2), c(105,-13)) z <- rbind(cbind(object=1, part=1, x1), cbind(object=2, part=1, x2), cbind(object=3, part=1, x3), cbind(object=3, part=2, x4)) colnames(z)[3:4] <- c('x', 'y') z <- cbind(z, hole=0) z[(z[, "object"]==3 & z[,"part"]==2), "hole"] <- 1 p <- vect(z, "polygons") geom(p) f <- system.file("ex/lux.shp", package="terra") v <- vect(f) g <- geom(v) head(g) w <- geom(v, wkt=TRUE) substr(w, 1, 60)
x1 <- rbind(c(-175,-20), c(-140,55), c(10, 0), c(-140,-60)) x2 <- rbind(c(-125,0), c(0,60), c(40,5), c(15,-45)) x3 <- rbind(c(-10,0), c(140,60), c(160,0), c(140,-55)) x4 <- rbind(c(80,0), c(105,13), c(120,2), c(105,-13)) z <- rbind(cbind(object=1, part=1, x1), cbind(object=2, part=1, x2), cbind(object=3, part=1, x3), cbind(object=3, part=2, x4)) colnames(z)[3:4] <- c('x', 'y') z <- cbind(z, hole=0) z[(z[, "object"]==3 & z[,"part"]==2), "hole"] <- 1 p <- vect(z, "polygons") geom(p) f <- system.file("ex/lux.shp", package="terra") v <- vect(f) g <- geom(v) head(g) w <- geom(v, wkt=TRUE) substr(w, 1, 60)
Get the geometry type (points, lines, or polygons) of a SpatVector. See datatype
for the data types of the fields (attributes, variables) of a SpatVector.
## S4 method for signature 'SpatVector' geomtype(x) ## S4 method for signature 'SpatVector' is.points(x) ## S4 method for signature 'SpatVector' is.lines(x) ## S4 method for signature 'SpatVector' is.polygons(x)
## S4 method for signature 'SpatVector' geomtype(x) ## S4 method for signature 'SpatVector' is.points(x) ## S4 method for signature 'SpatVector' is.lines(x) ## S4 method for signature 'SpatVector' is.polygons(x)
x |
SpatVector |
character
f <- system.file("ex/lux.shp", package="terra") v <- vect(f) geomtype(v) is.polygons(v) is.lines(v) is.points(v) names(v) datatype(v)
f <- system.file("ex/lux.shp", package="terra") v <- vect(f) geomtype(v) is.polygons(v) is.lines(v) is.points(v) names(v) datatype(v)
Compute global statistics, that is summarized values of an entire SpatRaster.
If x
is very large global
can fail, except when fun
is one of these built-in functions "mean", "min", "max", "sum", "prod", "range" (min and max), "rms" (root mean square), "sd" (sample standard deviation), "std" (population standard deviation), "isNA" (number of cells that are NA), "notNA" (number of cells that are not NA).
The reason that this can fail with large raster and a custom function is that all values need to be loaded into memory. To circumvent this problem you can run global
with a sample of the cells.
You can compute a weighted mean or sum by providing a SpatRaster with weights.
## S4 method for signature 'SpatRaster' global(x, fun="mean", weights=NULL, maxcell=Inf, ...)
## S4 method for signature 'SpatRaster' global(x, fun="mean", weights=NULL, maxcell=Inf, ...)
x |
SpatRaster |
fun |
function to be applied to summarize the values by zone. Either as one or more of these built-in character values: "max", "min", "mean", "sum", "range", "rms" (root mean square), "sd", "std" (population sd, using |
... |
additional arguments passed on to |
weights |
NULL or SpatRaster |
maxcell |
positive integer used to take a regular sample of |
A data.frame
with a row for each layer
zonal
for "zonal" statistics, and app
or Summary-methods
for "local" statistics, and extract
for summarizing values for polygons. Also see focal
for "focal" or "moving window" operations.
r <- rast(ncols=10, nrows=10) values(r) <- 1:ncell(r) global(r, "sum") global(r, "mean", na.rm=TRUE) x <- c(r, r/10) global(x, c("sum", "mean", "sd"), na.rm=TRUE) global(x, function(i) min(i) / max(i))
r <- rast(ncols=10, nrows=10) values(r) <- 1:ncell(r) global(r, "sum") global(r, "mean", na.rm=TRUE) x <- c(r, r/10) global(x, c("sum", "mean", "sd"), na.rm=TRUE) global(x, function(i) min(i) / max(i))
Create a graticule. That is, a grid of lon/lat lines that can be used to on a projected map.
The object returned, a SpatGraticule, can be plotted with plot
and lines
. There is also a crop
method.
graticule(lon=30, lat=30, crs="")
graticule(lon=30, lat=30, crs="")
lon |
numeric. Either a single number (the interval between longitudes), or a vector with longitudes |
lat |
numeric. Either a single number (the interval between latitudes), or a vector with latitudes |
crs |
character. The coordinate reference system to use |
SpatGraticule
g <- graticule(60, 30, crs="+proj=robin") g graticule(90, c(-90, -60, -23.5, 0, 23.5, 60, 90), crs="+proj=robin")
g <- graticule(60, 30, crs="+proj=robin") g graticule(90, c(-90, -60, -23.5, 0, 23.5, 60, 90), crs="+proj=robin")
The function calculates the distance to cells of a SpatRaster when the path has to go through the centers of the eight neighboring raster cells.
The default distance (when scale=1
, is meters if the coordinate reference system (CRS) of the SpatRaster is longitude/latitude (+proj=longlat
) and in the linear units of the CRS (typically meters) in other cases.
Distances are computed by summing local distances between cells, which are connected with their neighbors in 8 directions.
The shortest distance to the cells with the target
value is computed for all cells that are not NA
. Cells that are NA
cannot be traversed and are ignored, unless the target itself is NA
, in which case the distance to the nearest cell that is not NA
is computed for all cells that are NA
.
## S4 method for signature 'SpatRaster' gridDist(x, target=0, scale=1, maxiter=50, filename="", ...)
## S4 method for signature 'SpatRaster' gridDist(x, target=0, scale=1, maxiter=50, filename="", ...)
x |
SpatRaster |
target |
numeric. value of the target cells (where to compute distance to) |
scale |
numeric. Scale factor. For longitude/latitude data 1 = "m" and 1000 = "km". For planar data that is also the case of the distance unit of the crs is "m" |
maxiter |
numeric. The maximum number of iterations. Increase this number if you get the warning that |
filename |
character. output filename (optional) |
... |
additional arguments as for |
SpatRaster
See distance
for "as the crow flies" distance, and costDist
for distance across a landscape with variable friction
# global lon/lat raster r <- rast(ncol=10,nrow=10, vals=1) r[48] <- 0 r[66:68] <- NA d <- gridDist(r) plot(d) # planar crs(r) <- "+proj=utm +zone=15 +ellps=GRS80 +datum=NAD83 +units=m +no_defs" d <- gridDist(r) plot(d) # distance to cells that are not NA rr <- classify(r, cbind(1, NA)) dd <- gridDist(rr, NA)
# global lon/lat raster r <- rast(ncol=10,nrow=10, vals=1) r[48] <- 0 r[66:68] <- NA d <- gridDist(r) plot(d) # planar crs(r) <- "+proj=utm +zone=15 +ellps=GRS80 +datum=NAD83 +units=m +no_defs" d <- gridDist(r) plot(d) # distance to cells that are not NA rr <- classify(r, cbind(1, NA)) dd <- gridDist(rr, NA)
Add text to a plot that has a "halo". That is, a buffer around it to enhance visibility.
halo(x, y=NULL, labels, col="black", hc="white", hw=0.1, ...)
halo(x, y=NULL, labels, col="black", hc="white", hw=0.1, ...)
x , y
|
numeric. coordinates where the text labels should be written |
labels |
character. The text to be written |
col |
character. The main color to be used |
hc |
character. The halo color |
hw |
numeric. The halo width |
... |
additional arguments to pass to |
r <- rast(nrows=4, ncols=4) values(r) <- 1:ncell(r) plot(r, col="blue", legend=FALSE) text(-100, 20, "hello", cex=2) halo(50, 20, "hello", cex=2) halo(0, -20, "world", font=3, hc="light blue", cex=2, hw=.2) halo(0, 90, "world", font=2, cex=2, hw=.2, xpd=TRUE, pos=2) halo(0, 90, "world", col="white", font=2, hc="blue", cex=2, hw=.2, xpd=TRUE, pos=4)
r <- rast(nrows=4, ncols=4) values(r) <- 1:ncell(r) plot(r, col="blue", legend=FALSE) text(-100, 20, "hello", cex=2) halo(50, 20, "hello", cex=2) halo(0, -20, "world", font=3, hc="light blue", cex=2, hw=.2) halo(0, 90, "world", font=2, cex=2, hw=.2, xpd=TRUE, pos=2) halo(0, 90, "world", col="white", font=2, hc="blue", cex=2, hw=.2, xpd=TRUE, pos=4)
Show the head (first values) or tail (last values) of a SpatRaster or of the attributes of a SpatVector.
head(x, ...) tail(x, ...)
head(x, ...) tail(x, ...)
x |
SpatRaster or SpatVector |
... |
additional arguments passed on to other methods |
matrix (SpatRaster) or data.frame (SpatVector)
r <- rast(nrows=25, ncols=25) values(r) <- 1:ncell(r) head(r) tail(r)
r <- rast(nrows=25, ncols=25) values(r) <- 1:ncell(r) head(r) tail(r)
Create a histogram of the values of a SpatRaster. For large datasets a sample of maxcell
is used.
## S4 method for signature 'SpatRaster' hist(x, layer, maxcell=1000000, plot=TRUE, maxnl=16, main, ...)
## S4 method for signature 'SpatRaster' hist(x, layer, maxcell=1000000, plot=TRUE, maxnl=16, main, ...)
x |
SpatRaster |
layer |
positive integer or character to indicate layer numbers (or names). If missing, all layers up to |
maxcell |
integer. To regularly sample very large objects |
plot |
logical. Plot the histogram or only return the histogram values |
maxnl |
positive integer. The maximum number of layers to use. Ignored if |
main |
character. Main title(s) for the plot. Default is the value of |
... |
additional arguments. See |
This function is principally used for plotting a histogram, but it also returns an object of class "histogram" (invisibly if plot=TRUE
).
r1 <- r2 <- rast(nrows=50, ncols=50) values(r1) <- runif(ncell(r1)) values(r2) <- runif(ncell(r1)) rs <- r1 + r2 rp <- r1 * r2 opar <- par(no.readonly =TRUE) par(mfrow=c(2,2)) plot(rs, main='sum') plot(rp, main='product') hist(rs) a <- hist(rp) a x <- c(rs, rp, sqrt(rs)) hist(x) par(opar)
r1 <- r2 <- rast(nrows=50, ncols=50) values(r1) <- runif(ncell(r1)) values(r2) <- runif(ncell(r1)) rs <- r1 + r2 rp <- r1 * r2 opar <- par(no.readonly =TRUE) par(mfrow=c(2,2)) plot(rs, main='sum') plot(rp, main='product') hist(rs) a <- hist(rp) a x <- c(rs, rp, sqrt(rs)) hist(x) par(opar)
Compare two SpatRasters for equality.
First the attributes of the objects are compared. If these are the same, a the raster cells are compared as well. This can be time consuming, and you may prefer to use a sample instead with all.equal
## S4 method for signature 'SpatRaster,SpatRaster' identical(x, y)
## S4 method for signature 'SpatRaster,SpatRaster' identical(x, y)
x |
SpatRaster |
y |
SpatRaster |
single logical value
x <- sqrt(1:100) mat <- matrix(x, 10, 10) r1 <- rast(nrows=10, ncols=10, xmin=0, vals = x) r2 <- rast(nrows=10, ncols=10, xmin=0, vals = t(mat)) identical(r1, r2) identical(r1, r1*1) identical(rast(r1), rast(r2))
x <- sqrt(1:100) mat <- matrix(x, 10, 10) r1 <- rast(nrows=10, ncols=10, xmin=0, vals = x) r2 <- rast(nrows=10, ncols=10, xmin=0, vals = t(mat)) identical(r1, r2) identical(r1, r1*1) identical(rast(r1), rast(r2))
Implementation of ifelse
for SpatRasters. This method allows for a concise expression of what can otherwise be achieved with a combination of classify
, mask
, and cover
.
ifel
is an R
equivalent to the Con
method in ArcGIS (arcpy).
## S4 method for signature 'SpatRaster' ifel(test, yes, no, filename="", ...)
## S4 method for signature 'SpatRaster' ifel(test, yes, no, filename="", ...)
test |
SpatRaster with logical (TRUE/FALSE) values |
yes |
SpatRaster or numeric |
no |
SpatRaster or numeric |
filename |
character. Output filename |
... |
additional arguments for writing files as in |
SpatRaster
r <- rast(nrows=5, ncols=5, xmin=0, xmax=1, ymin=0, ymax=1) values(r) <- c(-10:0, NA, NA, NA, 0:10) x <- ifel(r > 1, 1, r) # same as a <- classify(r, cbind(1, Inf, 1)) # or b <- app(r, fun=function(i) {i[i > 1] <- 1; i}) # or d <- clamp(r, -Inf, 1) # or (not recommended for large datasets) e <- r e[e>1] <- 1 ## other examples f <- ifel(is.na(r), 100, r) z <- ifel(r > -2 & r < 2, 100, 0) # nested expressions y <- ifel(r > 1, 1, ifel(r < -1, -1, r)) k <- ifel(r > 0, r+10, ifel(r < 0, r-10, 3))
r <- rast(nrows=5, ncols=5, xmin=0, xmax=1, ymin=0, ymax=1) values(r) <- c(-10:0, NA, NA, NA, 0:10) x <- ifel(r > 1, 1, r) # same as a <- classify(r, cbind(1, Inf, 1)) # or b <- app(r, fun=function(i) {i[i > 1] <- 1; i}) # or d <- clamp(r, -Inf, 1) # or (not recommended for large datasets) e <- r e[e>1] <- 1 ## other examples f <- ifel(is.na(r), 100, r) z <- ifel(r > -2 & r < 2, 100, 0) # nested expressions y <- ifel(r > 1, 1, ifel(r < -1, -1, r)) k <- ifel(r > 0, r+10, ifel(r < 0, r-10, 3))
Plot (make a map of) the values of a SpatRaster via image
. See plot
if you need more fancy options such as a legend.
## S4 method for signature 'SpatRaster' image(x, y=1, maxcell=500000, ...)
## S4 method for signature 'SpatRaster' image(x, y=1, maxcell=500000, ...)
x |
SpatRaster |
y |
positive integer indicating the layer to be plotted, or a character indicating the name of the layer |
maxcell |
positive integer. Maximum number of cells to use for the plot |
... |
additional arguments as for |
f <- system.file("ex/elev.tif", package="terra") r <- rast(f) image(r) image(r, col=rainbow(24))
f <- system.file("ex/elev.tif", package="terra") r <- rast(f) image(r) image(r, col=rainbow(24))
Warp the members of a SpatRasterCollection to match the geometry of a SpatRaster.
## S4 method for signature 'SpatRasterCollection' impose(x, y, filename="", ...)
## S4 method for signature 'SpatRasterCollection' impose(x, y, filename="", ...)
x |
SpatRasterCollection |
y |
SpatRaster |
filename |
character. Output filename |
... |
list with named options for writing files as in |
SpatRaster
Create a SpatRaster with values reflecting a cell property: "x", "y", "col", "row", "cell" or "chess". Alternatively, a function can be used. In that case, cell values are initialized without reference to pre-existing values. E.g., initialize with a random number (fun=runif
). While there are more direct ways of achieving this for small objects (see examples) for which a vector with all values can be created in memory, the init
function will also work for SpatRasters with many cells.
## S4 method for signature 'SpatRaster' init(x, fun, filename="", ...)
## S4 method for signature 'SpatRaster' init(x, fun, filename="", ...)
x |
SpatRaster |
fun |
function to be applied. This must be a either single number, multiple numbers, a function, or one of a set of known character values. A function must take the number of cells as a single argument to return a vector of values with a length equal to the number of cells, such as |
filename |
character. Output filename |
... |
additional arguments for writing files as in |
SpatRaster
r <- rast(ncols=10, nrows=5, xmin=0, xmax=10, ymin=0, ymax=5) x <- init(r, fun="cell") y <- init(r, fun=runif) # initialize with a single value z <- init(r, fun=8)
r <- rast(ncols=10, nrows=5, xmin=0, xmax=10, ymin=0, ymax=5) x <- init(r, fun="cell") y <- init(r, fun=runif) # initialize with a single value z <- init(r, fun=8)
These "in-place" replacement methods assign new value to an object without making a copy. That is efficient, but if there is a copy of the object that you made by standard assignment (e.g. with y <- x
), that copy is also changed.
set.names
is the in-place replacement version of names<-
.
set.ext
is the in-place replacement version of ext<-
set.values
is the in-place replacement version of [<-
.
set.cats
is the in-place replacement version of categories
set.crs
is the in-place replacement version of crs<-
## S4 method for signature 'SpatRaster' set.names(x, value, index=1:nlyr(x), validate=FALSE) ## S4 method for signature 'SpatRasterDataset' set.names(x, value, index=1:length(x), validate=FALSE) ## S4 method for signature 'SpatVector' set.names(x, value, index=1:ncol(x), validate=FALSE) ## S4 method for signature 'SpatRaster' set.ext(x, value) ## S4 method for signature 'SpatVector' set.ext(x, value) ## S4 method for signature 'SpatRaster' set.crs(x, value) ## S4 method for signature 'SpatVector' set.crs(x, value) ## S4 method for signature 'SpatRaster' set.values(x, cells, values, layer=0) ## S4 method for signature 'SpatRaster' set.cats(x, layer=1, value, active=1) ## S4 method for signature 'SpatRaster' set.RGB(x, value, type="rgb")
## S4 method for signature 'SpatRaster' set.names(x, value, index=1:nlyr(x), validate=FALSE) ## S4 method for signature 'SpatRasterDataset' set.names(x, value, index=1:length(x), validate=FALSE) ## S4 method for signature 'SpatVector' set.names(x, value, index=1:ncol(x), validate=FALSE) ## S4 method for signature 'SpatRaster' set.ext(x, value) ## S4 method for signature 'SpatVector' set.ext(x, value) ## S4 method for signature 'SpatRaster' set.crs(x, value) ## S4 method for signature 'SpatVector' set.crs(x, value) ## S4 method for signature 'SpatRaster' set.values(x, cells, values, layer=0) ## S4 method for signature 'SpatRaster' set.cats(x, layer=1, value, active=1) ## S4 method for signature 'SpatRaster' set.RGB(x, value, type="rgb")
x |
SpatRaster |
value |
character for |
index |
positive integer indicating layer(s) to assign a name to |
validate |
logical. Make names valid and/or unique? |
cells |
cell numbers or missing |
values |
replacement values or missing to load all values into memory |
layer |
positive integer(s) indicating to which layer(s) to you want to assign these categories or to which you want to set these values. A number < 1 indicates "all layers" |
active |
positive integer indicating the active category (column number in |
type |
character. The color space. One of "rgb" "hsv", "hsi" and "hsl" |
logical (invisibly)
s <- rast(ncols=5, nrows=5, nlyrs=3) x <- s names(s) names(s) <- c("a", "b", "c") names(s) names(x) x <- s set.names(s, c("e", "f", "g")) names(s) names(x) set.ext(x, c(0,180,0,90)) f <- system.file("ex/elev.tif", package="terra") r <- rast(f) #values from file to memory set.values(r) # change values set.values(r, 1:1000, 900)
s <- rast(ncols=5, nrows=5, nlyrs=3) x <- s names(s) names(s) <- c("a", "b", "c") names(s) names(x) x <- s set.names(s, c("e", "f", "g")) names(s) names(x) set.ext(x, c(0,180,0,90)) f <- system.file("ex/elev.tif", package="terra") r <- rast(f) #values from file to memory set.values(r) # change values set.values(r, 1:1000, 900)
Make an inset map or scale the extent of a SpatVector
## S4 method for signature 'SpatVector' inset(x, e, loc="", scale=0.2, background="white", perimeter=TRUE, box=NULL, pper, pbox, offset=0.1, add=TRUE, ...) ## S4 method for signature 'SpatRaster' inset(x, e, loc="", scale=0.2, background="white", perimeter=TRUE, box=NULL, pper, pbox, offset=0.1, add=TRUE, ...) ## S4 method for signature 'SpatVector' inext(x, e, y=NULL, gap=0)
## S4 method for signature 'SpatVector' inset(x, e, loc="", scale=0.2, background="white", perimeter=TRUE, box=NULL, pper, pbox, offset=0.1, add=TRUE, ...) ## S4 method for signature 'SpatRaster' inset(x, e, loc="", scale=0.2, background="white", perimeter=TRUE, box=NULL, pper, pbox, offset=0.1, add=TRUE, ...) ## S4 method for signature 'SpatVector' inext(x, e, y=NULL, gap=0)
x |
SpatVector, SpatRaster |
e |
SpatExtent to set the size and location of the inset. Or missing |
loc |
character. One of "bottomright", "bottom", "bottomleft", "left", "topleft", "top", "topright", "right", "center" |
scale |
numeric. The relative size of the inset, used when x is missing |
background |
color for the background of the inset. Use |
perimeter |
logical. If |
box |
SpatExtent or missing, to draw a box on the inset, e.g. to show where the map is located in a larger area |
pper |
list with graphical parameters (arguments) such as |
pbox |
list with graphical parameters (arguments) such as |
offset |
numeric. Value between 0.1 and 1 to indicate the relative distance between what is mapped and the bounding box |
add |
logical. Add the inset to the map? |
... |
additional arguments passed to plot for the drawing of |
y |
SpatVector. If not NULL, |
gap |
numeric to add space between the SpatVector and the SpatExtent |
scaled and shifted SpatVector or SpatRaster (returned invisibly)
f <- system.file("ex/lux.shp", package="terra") v <- vect(f) x <- v[v$NAME_2 == "Diekirch", ] plot(x, density=10, col="blue") inset(v) # more elaborate plot(x, density=10, col="blue") inset(v, col = "brown", border="lightgrey", perimeter=TRUE, pper=list(col="orange", lwd=3, lty=2), box=ext(x), pbox=list(col="blue", lwd=2)) cols <- rep("light grey", 12) cols[2] <- "red" e <- ext(c(6.2, 6.3, 49.9, 50)) b <- ext(x)+0.02 inset(v, e=e, col=cols, box=b) # with a SpatRaster ff <- system.file("ex/elev.tif", package="terra") r <- rast(ff) r <- crop(r, ext(x) + .01) plot(r, type="int", mar=c(2,2,2,2), plg=list(x="topright")) lines(v, lwd=1.5) lines(x, lwd=2.5) inset(v, col=cols, loc="topleft", scale=0.15) # a more complex one plot(r, plg=list(title="meter\n", shrink=.2, cex=.8)) lines(v, lwd=4, col="white") lines(v, lwd=1.5) lines(x, lwd=2.5) text(x, "NAME_2", cex=1.5, halo=TRUE) sbar(6, c(6.04, 49.785), type="bar", below="km", label=c(0,3,6), cex=.8) s <- inset(v, col=cols, box=b, scale=.2, loc="topright", background="light yellow", pbox=list(lwd=2, lty=5, col="blue")) # note the returned inset SpatVector s lines(s, col="orange")
f <- system.file("ex/lux.shp", package="terra") v <- vect(f) x <- v[v$NAME_2 == "Diekirch", ] plot(x, density=10, col="blue") inset(v) # more elaborate plot(x, density=10, col="blue") inset(v, col = "brown", border="lightgrey", perimeter=TRUE, pper=list(col="orange", lwd=3, lty=2), box=ext(x), pbox=list(col="blue", lwd=2)) cols <- rep("light grey", 12) cols[2] <- "red" e <- ext(c(6.2, 6.3, 49.9, 50)) b <- ext(x)+0.02 inset(v, e=e, col=cols, box=b) # with a SpatRaster ff <- system.file("ex/elev.tif", package="terra") r <- rast(ff) r <- crop(r, ext(x) + .01) plot(r, type="int", mar=c(2,2,2,2), plg=list(x="topright")) lines(v, lwd=1.5) lines(x, lwd=2.5) inset(v, col=cols, loc="topleft", scale=0.15) # a more complex one plot(r, plg=list(title="meter\n", shrink=.2, cex=.8)) lines(v, lwd=4, col="white") lines(v, lwd=1.5) lines(x, lwd=2.5) text(x, "NAME_2", cex=1.5, halo=TRUE) sbar(6, c(6.04, 49.785), type="bar", below="km", label=c(0,3,6), cex=.8) s <- inset(v, col=cols, box=b, scale=.2, loc="topright", background="light yellow", pbox=list(lwd=2, lty=5, col="blue")) # note the returned inset SpatVector s lines(s, col="orange")
Interpolate points within a moving window using inverse distance weighting. The maximum number of points used can be restricted, optionally by selecting the nearest points.
## S4 method for signature 'SpatRaster,SpatVector' interpIDW(x, y, field, radius, power=2, smooth=0, maxPoints=Inf, minPoints=1, near=TRUE, fill=NA, filename="", ...) ## S4 method for signature 'SpatRaster,matrix' interpIDW(x, y, radius, power=2, smooth=0, maxPoints=Inf, minPoints=1, near=TRUE, fill=NA, filename="", ...)
## S4 method for signature 'SpatRaster,SpatVector' interpIDW(x, y, field, radius, power=2, smooth=0, maxPoints=Inf, minPoints=1, near=TRUE, fill=NA, filename="", ...) ## S4 method for signature 'SpatRaster,matrix' interpIDW(x, y, radius, power=2, smooth=0, maxPoints=Inf, minPoints=1, near=TRUE, fill=NA, filename="", ...)
x |
SpatRaster |
y |
SpatVector or matrix with three columns (x,y,z) |
field |
character. field name in SpatVector |
radius |
numeric. The radius of the circle (single number). If |
power |
numeric. Weighting power |
smooth |
numeric. Smoothing parameter |
minPoints |
numeric. The minimum number of points to use. If fewer points are found in a search ellipse it is considered empty and the fill value is returned |
maxPoints |
numeric. The maximum number of points to consider in a search area. Additional points are ignored. If fewer points are found, the fill value is returned |
near |
logical. Should the nearest points within the neighborhood be used if |
fill |
numeric. value to use to fill empty cells |
filename |
character. Output filename |
... |
additional arguments for writing files as in |
SpatRaster
rasterizeWin, rasterize, interpNear, interpolate
r <- rast(ncol=100, nrow=100, crs="local", xmin=0, xmax=50, ymin=0, ymax=50) set.seed(100) x <- runif(25, 5, 45) y <- runif(25, 5, 45) z <- sample(25) xyz <- cbind(x,y,z) x <- interpIDW(r, xyz, radius=5, power=1, smooth=1, maxPoints=5)
r <- rast(ncol=100, nrow=100, crs="local", xmin=0, xmax=50, ymin=0, ymax=50) set.seed(100) x <- runif(25, 5, 45) y <- runif(25, 5, 45) z <- sample(25) xyz <- cbind(x,y,z) x <- interpIDW(r, xyz, radius=5, power=1, smooth=1, maxPoints=5)
Nearest neighbor interpolation of points, using a moving window
## S4 method for signature 'SpatRaster,SpatVector' interpNear(x, y, field, radius, interpolate=FALSE, fill=NA, filename="", ...) ## S4 method for signature 'SpatRaster,matrix' interpNear(x, y, radius, interpolate=FALSE, fill=NA, filename="", ...)
## S4 method for signature 'SpatRaster,SpatVector' interpNear(x, y, field, radius, interpolate=FALSE, fill=NA, filename="", ...) ## S4 method for signature 'SpatRaster,matrix' interpNear(x, y, radius, interpolate=FALSE, fill=NA, filename="", ...)
x |
SpatRaster |
y |
SpatVector or matrix with three columns (x,y,z) |
field |
character. field name in SpatVector |
radius |
numeric. The radius of the circle (single number). If |
interpolate |
logical. Should the nearest neighbor values be linearly interpolated between points? |
fill |
numeric. value to use to fill empty cells |
filename |
character. Output filename |
... |
additional arguments for writing files as in |
SpatRaster
rasterizeWin, rasterize, interpIDW, interpolate
r <- rast(ncol=100, nrow=100, crs="local", xmin=0, xmax=50, ymin=0, ymax=50) set.seed(100) x <- runif(25, 5, 45) y <- runif(25, 5, 45) z <- sample(25) xyz <- cbind(x,y,z) x <- interpNear(r, xyz, radius=5) p <- vect(data.frame(xyz), geom=c("x", "y")) v <- voronoi(p) plot(x, col=rainbow(25)) lines(v) # plot(v, col=rainbow(25)); points(p)
r <- rast(ncol=100, nrow=100, crs="local", xmin=0, xmax=50, ymin=0, ymax=50) set.seed(100) x <- runif(25, 5, 45) y <- runif(25, 5, 45) z <- sample(25) xyz <- cbind(x,y,z) x <- interpNear(r, xyz, radius=5) p <- vect(data.frame(xyz), geom=c("x", "y")) v <- voronoi(p) plot(x, col=rainbow(25)) lines(v) # plot(v, col=rainbow(25)); points(p)
Make a SpatRaster with interpolated values using a fitted model object of classes such as "gstat" (gstat package) or "Krige" (fields package), or any other model that has location (e.g., "x" and "y", or "longitude" and "latitude") as predictors (independent variables). If x and y are the only predictors, it is most efficient if you provide an empty (no associated data in memory or on file) SpatRaster for which you want predictions. If there are more spatial predictor variables, provide these as a SpatRaster in the first argument of the function. If you do not have x and y locations as implicit predictors in your model you should use predict
instead.
## S4 method for signature 'SpatRaster' interpolate(object, model, fun=predict, ..., xyNames=c("x", "y"), factors=NULL, const=NULL, index = NULL, cores=1, cpkgs=NULL, na.rm=FALSE, filename="", overwrite=FALSE, wopt=list())
## S4 method for signature 'SpatRaster' interpolate(object, model, fun=predict, ..., xyNames=c("x", "y"), factors=NULL, const=NULL, index = NULL, cores=1, cpkgs=NULL, na.rm=FALSE, filename="", overwrite=FALSE, wopt=list())
object |
SpatRaster |
model |
model object |
fun |
function. Default value is "predict", but can be replaced with e.g. "predict.se" (depending on the class of |
... |
additional arguments passed to |
xyNames |
character. variable names that the model uses for the spatial coordinates. E.g., |
factors |
list with levels for factor variables. The list elements should be named with names that correspond to names in |
const |
data.frame. Can be used to add a constant for which there is no SpatRaster for model predictions. This is particularly useful if the constant is a character-like factor value |
index |
positive integer or NULL. Allows for selecting of the variable returned if the model returns multiple variables |
cores |
positive integer. If |
cpkgs |
character. The package(s) that need to be loaded on the nodes to be able to run the model.predict function (see examples in |
na.rm |
logical. If |
filename |
character. Output filename |
overwrite |
logical. If |
wopt |
list with named options for writing files as in |
SpatRaster
predict
, interpIDW
, interpNear
r <- rast(system.file("ex/elev.tif", package="terra")) ra <- aggregate(r, 10) xy <- data.frame(xyFromCell(ra, 1:ncell(ra))) v <- values(ra) i <- !is.na(v) xy <- xy[i,] v <- v[i] ## Not run: library(fields) tps <- Tps(xy, v) p <- rast(r) # use model to predict values at all locations p <- interpolate(p, tps) p <- mask(p, r) plot(p) ### change "fun" from predict to fields::predictSE to get the TPS standard error ## need to use "rast(p)" to remove the values se <- interpolate(rast(p), tps, fun=predictSE) se <- mask(se, r) plot(se) ### another predictor variable, "e" e <- (init(r, "x") * init(r, "y")) / 100000000 names(e) <- "e" z <- as.matrix(extract(e, xy)[,-1]) ## add as another independent variable xyz <- cbind(xy, z) tps2 <- Tps(xyz, v) p2 <- interpolate(e, tps2, xyOnly=FALSE) ## as a linear covariate tps3 <- Tps(xy, v, Z=z) ## Z is a separate argument in Krig.predict, so we need a new function ## Internally (in interpolate) a matrix is formed of x, y, and elev (Z) pfun <- function(model, x, ...) { predict(model, x[,1:2], Z=x[,3], ...) } p3 <- interpolate(e, tps3, fun=pfun) #### gstat examples library(gstat) library(sp) data(meuse) ### inverse distance weighted (IDW) r <- rast(system.file("ex/meuse.tif", package="terra")) mg <- gstat(id = "zinc", formula = zinc~1, locations = ~x+y, data=meuse, nmax=7, set=list(idp = .5)) z <- interpolate(r, mg, debug.level=0, index=1) z <- mask(z, r) ## with a model built with an `sf` object you need to provide custom function library(sf) sfmeuse <- st_as_sf(meuse, coords = c("x", "y"), crs=crs(r)) mgsf <- gstat(id = "zinc", formula = zinc~1, data=sfmeuse, nmax=7, set=list(idp = .5)) interpolate_gstat <- function(model, x, crs, ...) { v <- st_as_sf(x, coords=c("x", "y"), crs=crs) p <- predict(model, v, ...) as.data.frame(p)[,1:2] } zsf <- interpolate(r, mgsf, debug.level=0, fun=interpolate_gstat, crs=crs(r), index=1) zsf <- mask(zsf, r) ### kriging ### ordinary kriging v <- variogram(log(zinc)~1, ~x+y, data=meuse) mv <- fit.variogram(v, vgm(1, "Sph", 300, 1)) gOK <- gstat(NULL, "log.zinc", log(zinc)~1, meuse, locations=~x+y, model=mv) OK <- interpolate(r, gOK, debug.level=0) ## universal kriging vu <- variogram(log(zinc)~elev, ~x+y, data=meuse) mu <- fit.variogram(vu, vgm(1, "Sph", 300, 1)) gUK <- gstat(NULL, "log.zinc", log(zinc)~elev, meuse, locations=~x+y, model=mu) names(r) <- "elev" UK <- interpolate(r, gUK, debug.level=0) ## co-kriging gCoK <- gstat(NULL, 'log.zinc', log(zinc)~1, meuse, locations=~x+y) gCoK <- gstat(gCoK, 'elev', elev~1, meuse, locations=~x+y) gCoK <- gstat(gCoK, 'cadmium', cadmium~1, meuse, locations=~x+y) gCoK <- gstat(gCoK, 'copper', copper~1, meuse, locations=~x+y) coV <- variogram(gCoK) plot(coV, type='b', main='Co-variogram') coV.fit <- fit.lmc(coV, gCoK, vgm(model='Sph', range=1000)) coV.fit plot(coV, coV.fit, main='Fitted Co-variogram') coK <- interpolate(r, coV.fit, debug.level=0) plot(coK) ## End(Not run)
r <- rast(system.file("ex/elev.tif", package="terra")) ra <- aggregate(r, 10) xy <- data.frame(xyFromCell(ra, 1:ncell(ra))) v <- values(ra) i <- !is.na(v) xy <- xy[i,] v <- v[i] ## Not run: library(fields) tps <- Tps(xy, v) p <- rast(r) # use model to predict values at all locations p <- interpolate(p, tps) p <- mask(p, r) plot(p) ### change "fun" from predict to fields::predictSE to get the TPS standard error ## need to use "rast(p)" to remove the values se <- interpolate(rast(p), tps, fun=predictSE) se <- mask(se, r) plot(se) ### another predictor variable, "e" e <- (init(r, "x") * init(r, "y")) / 100000000 names(e) <- "e" z <- as.matrix(extract(e, xy)[,-1]) ## add as another independent variable xyz <- cbind(xy, z) tps2 <- Tps(xyz, v) p2 <- interpolate(e, tps2, xyOnly=FALSE) ## as a linear covariate tps3 <- Tps(xy, v, Z=z) ## Z is a separate argument in Krig.predict, so we need a new function ## Internally (in interpolate) a matrix is formed of x, y, and elev (Z) pfun <- function(model, x, ...) { predict(model, x[,1:2], Z=x[,3], ...) } p3 <- interpolate(e, tps3, fun=pfun) #### gstat examples library(gstat) library(sp) data(meuse) ### inverse distance weighted (IDW) r <- rast(system.file("ex/meuse.tif", package="terra")) mg <- gstat(id = "zinc", formula = zinc~1, locations = ~x+y, data=meuse, nmax=7, set=list(idp = .5)) z <- interpolate(r, mg, debug.level=0, index=1) z <- mask(z, r) ## with a model built with an `sf` object you need to provide custom function library(sf) sfmeuse <- st_as_sf(meuse, coords = c("x", "y"), crs=crs(r)) mgsf <- gstat(id = "zinc", formula = zinc~1, data=sfmeuse, nmax=7, set=list(idp = .5)) interpolate_gstat <- function(model, x, crs, ...) { v <- st_as_sf(x, coords=c("x", "y"), crs=crs) p <- predict(model, v, ...) as.data.frame(p)[,1:2] } zsf <- interpolate(r, mgsf, debug.level=0, fun=interpolate_gstat, crs=crs(r), index=1) zsf <- mask(zsf, r) ### kriging ### ordinary kriging v <- variogram(log(zinc)~1, ~x+y, data=meuse) mv <- fit.variogram(v, vgm(1, "Sph", 300, 1)) gOK <- gstat(NULL, "log.zinc", log(zinc)~1, meuse, locations=~x+y, model=mv) OK <- interpolate(r, gOK, debug.level=0) ## universal kriging vu <- variogram(log(zinc)~elev, ~x+y, data=meuse) mu <- fit.variogram(vu, vgm(1, "Sph", 300, 1)) gUK <- gstat(NULL, "log.zinc", log(zinc)~elev, meuse, locations=~x+y, model=mu) names(r) <- "elev" UK <- interpolate(r, gUK, debug.level=0) ## co-kriging gCoK <- gstat(NULL, 'log.zinc', log(zinc)~1, meuse, locations=~x+y) gCoK <- gstat(gCoK, 'elev', elev~1, meuse, locations=~x+y) gCoK <- gstat(gCoK, 'cadmium', cadmium~1, meuse, locations=~x+y) gCoK <- gstat(gCoK, 'copper', copper~1, meuse, locations=~x+y) coV <- variogram(gCoK) plot(coV, type='b', main='Co-variogram') coV.fit <- fit.lmc(coV, gCoK, vgm(model='Sph', range=1000)) coV.fit plot(coV, coV.fit, main='Fitted Co-variogram') coK <- interpolate(r, coV.fit, debug.level=0) plot(coK) ## End(Not run)
You can intersect SpatVectors with each other or with a SpatExtent. Intersecting points with points uses the extent of y
to get the intersection. Intersecting of points and lines is not supported because of numerical inaccuracies with that. You can use buffer
, to create polygons from lines and use these with intersect.
You can also intersect two SpatExtents.
When intersecting two SpatRasters these need to be aligned (have the same origin and spatial resolution). The values of the returned SpatRaster are TRUE
where both input rasters have values, FALSE
where one has values, and NA
in all other cells.
When intersecting a SpatExtent and a SpatRaster, the SpatExtent is first aligned to the raster cell boundaries.
See crop
for the intersection of a SpatRaster with a SpatExtent (or the extent of a SpatRaster or SpatVector) if you want a SpatRaster (not a SpatExtent) as output.
See is.related(x, y, "intersects")
to find out which geometries of a SpatVector intersect. You can spatially subset a SpatVector with another one with x[y]
.
## S4 method for signature 'SpatVector,SpatVector' intersect(x, y) ## S4 method for signature 'SpatVector,SpatExtent' intersect(x, y) ## S4 method for signature 'SpatExtent,SpatVector' intersect(x, y) ## S4 method for signature 'SpatExtent,SpatExtent' intersect(x, y) ## S4 method for signature 'SpatRaster,SpatRaster' intersect(x, y) ## S4 method for signature 'SpatRaster,SpatExtent' intersect(x, y) ## S4 method for signature 'SpatExtent,SpatRaster' intersect(x, y)
## S4 method for signature 'SpatVector,SpatVector' intersect(x, y) ## S4 method for signature 'SpatVector,SpatExtent' intersect(x, y) ## S4 method for signature 'SpatExtent,SpatVector' intersect(x, y) ## S4 method for signature 'SpatExtent,SpatExtent' intersect(x, y) ## S4 method for signature 'SpatRaster,SpatRaster' intersect(x, y) ## S4 method for signature 'SpatRaster,SpatExtent' intersect(x, y) ## S4 method for signature 'SpatExtent,SpatRaster' intersect(x, y)
x |
SpatVector, SpatExtent, or SpatRaster |
y |
SpatVector, SpatExtent, or SpatRaster |
Same as x
e1 <- ext(-10, 10, -20, 20) e2 <- ext(0, 20, -40, 5) intersect(e1, e2) f <- system.file("ex/lux.shp", package="terra") v <- vect(f) e <- ext(5.6, 6, 49.55, 49.7) x <- intersect(v, e) p <- vect(c("POLYGON ((5.8 49.8, 6 49.9, 6.15 49.8, 6 49.6, 5.8 49.8))", "POLYGON ((6.3 49.9, 6.2 49.7, 6.3 49.6, 6.5 49.8, 6.3 49.9))"), crs=crs(v)) values(p) <- data.frame(pid=1:2, area=expanse(p)) y <- intersect(v, p) r <- s <- rast(ncol=5, nrow=5, xmin=1, xmax=5, ymin=1, ymax=5) r[5:20] <- 5:20 s[11:20] <- 11:20 rs <- intersect(r, s) u <- shift(r, .8) us <- intersect(u, s)
e1 <- ext(-10, 10, -20, 20) e2 <- ext(0, 20, -40, 5) intersect(e1, e2) f <- system.file("ex/lux.shp", package="terra") v <- vect(f) e <- ext(5.6, 6, 49.55, 49.7) x <- intersect(v, e) p <- vect(c("POLYGON ((5.8 49.8, 6 49.9, 6.15 49.8, 6 49.6, 5.8 49.8))", "POLYGON ((6.3 49.9, 6.2 49.7, 6.3 49.6, 6.5 49.8, 6.3 49.9))"), crs=crs(v)) values(p) <- data.frame(pid=1:2, area=expanse(p)) y <- intersect(v, p) r <- s <- rast(ncol=5, nrow=5, xmin=1, xmax=5, ymin=1, ymax=5) r[5:20] <- 5:20 s[11:20] <- 11:20 rs <- intersect(r, s) u <- shift(r, .8) us <- intersect(u, s)
The values in a SpatRaster layer are by default numeric, but they can also be set to be logical (Boolean), integer, or categorical (factor).
For a SpatRaster
, as.logical
and isTRUE
is equivalent to as.bool
. isFALSE
is equivalent to !as.bool
, and as.integer
is the same as as.int
.
as.bool
and as.int
force the values into the correct range (e.g. whole integers) but in-memory cell values are still stored as numeric. They will behave like the assigned types, though, and will be written to files with that data type (if the file type supports it).
See levels
and cats
to create categorical layers by setting labels.
## S4 method for signature 'SpatRaster' is.bool(x) ## S4 method for signature 'SpatRaster' as.bool(x, filename, ...) ## S4 method for signature 'SpatRaster' is.int(x) ## S4 method for signature 'SpatRaster' as.int(x, filename, ...) ## S4 method for signature 'SpatRaster' is.factor(x) ## S4 method for signature 'SpatRaster' as.factor(x)
## S4 method for signature 'SpatRaster' is.bool(x) ## S4 method for signature 'SpatRaster' as.bool(x, filename, ...) ## S4 method for signature 'SpatRaster' is.int(x) ## S4 method for signature 'SpatRaster' as.int(x, filename, ...) ## S4 method for signature 'SpatRaster' is.factor(x) ## S4 method for signature 'SpatRaster' as.factor(x)
x |
SpatRaster |
filename |
character. Output filename |
... |
list with named options for writing files as in |
The as.*
methods return a new SpatRaster
, whereas the is.*
methods return a logical
value for each layer in x
.
levels
and cats
to create categorical layers (and set labels).
r <- rast(nrows=10, ncols=10, vals=1:100) is.bool(r) z <- as.bool(r) is.bool(z) x <- r > 25 is.bool(x) rr <- r/2 is.int(rr) is.int(round(rr))
r <- rast(nrows=10, ncols=10, vals=1:100) is.bool(r) z <- as.bool(r) is.bool(z) x <- r > 25 is.bool(x) rr <- r/2 is.int(rr) is.int(round(rr))
An empty SpatExtent has no area
An empty SpatVector has no geometries.
## S4 method for signature 'SpatExtent' is.empty(x) ## S4 method for signature 'SpatVector' is.empty(x)
## S4 method for signature 'SpatExtent' is.empty(x) ## S4 method for signature 'SpatVector' is.empty(x)
x |
SpatVector or SpatExtent |
logical
e <- ext(0,0,0,0) is.valid(e) is.empty(e) v <- vect() is.valid(v) is.empty(v)
e <- ext(0,0,0,0) is.valid(e) is.empty(e) v <- vect() is.valid(v) is.empty(v)
Test whether a SpatRaster or SpatVector has a longitude/latitude coordinate reference system (CRS), or perhaps has one. That is, when the CRS is unknown (""
) but the x coordinates are within -181 and 181 and the y coordinates are within -90.1 and 90.1. For a SpatRaster you can also test if it has a longitude/latitude CRS and it is "global" (covers all longitudes).
A warning is given if the CRS is missing or if it is specified as longitude/latitude but the coordinates do not match that.
## S4 method for signature 'SpatRaster' is.lonlat(x, perhaps=FALSE, warn=TRUE, global=FALSE) ## S4 method for signature 'SpatVector' is.lonlat(x, perhaps=FALSE, warn=TRUE) ## S4 method for signature 'character' is.lonlat(x, perhaps=FALSE, warn=TRUE)
## S4 method for signature 'SpatRaster' is.lonlat(x, perhaps=FALSE, warn=TRUE, global=FALSE) ## S4 method for signature 'SpatVector' is.lonlat(x, perhaps=FALSE, warn=TRUE) ## S4 method for signature 'character' is.lonlat(x, perhaps=FALSE, warn=TRUE)
x |
SpatRaster or SpatVector |
perhaps |
logical. If |
warn |
logical. If |
global |
logical. If |
logical or NA
r <- rast() is.lonlat(r) is.lonlat(r, global=TRUE) crs(r) <- "" is.lonlat(r) is.lonlat(r, perhaps=TRUE, warn=FALSE) crs(r) <- "+proj=lcc +lat_1=48 +lat_2=33 +lon_0=-100 +ellps=WGS84" is.lonlat(r)
r <- rast() is.lonlat(r) is.lonlat(r, global=TRUE) crs(r) <- "" is.lonlat(r) is.lonlat(r, perhaps=TRUE, warn=FALSE) crs(r) <- "+proj=lcc +lat_1=48 +lat_2=33 +lon_0=-100 +ellps=WGS84" is.lonlat(r)
Check if a SpatRaster is "rotated" and needs to be rectified before it can be used
See rectify
## S4 method for signature 'SpatRaster' is.rotated(x)
## S4 method for signature 'SpatRaster' is.rotated(x)
x |
SpatRaster |
logical. One value for each raster data *source*
r <- rast(nrows=10, ncols=10, vals=1:100) is.rotated(r)
r <- rast(nrows=10, ncols=10, vals=1:100) is.rotated(r)
Check the validity of polygons or attempt to fix it. Or check the validity of a SpatExtent.
## S4 method for signature 'SpatVector' is.valid(x, messages=FALSE, as.points=FALSE) ## S4 method for signature 'SpatVector' makeValid(x) ## S4 method for signature 'SpatExtent' is.valid(x)
## S4 method for signature 'SpatVector' is.valid(x, messages=FALSE, as.points=FALSE) ## S4 method for signature 'SpatVector' makeValid(x) ## S4 method for signature 'SpatExtent' is.valid(x)
x |
SpatVector or SpatExtent |
messages |
logical. If |
as.points |
logical. If |
logical
w <- vect("POLYGON ((0 -5, 10 0, 10 -10, 0 -5))") is.valid(w) w <- vect("POLYGON ((0 -5, 10 0, 10 -10, 4 -2, 0 -5))") is.valid(w) is.valid(w, TRUE) plot(w) points(cbind(4.54, -2.72), cex=2, col="red") e <- ext(0, 1, 0, 1) is.valid(e) ee <- ext(0, 0, 0, 0) is.valid(ee)
w <- vect("POLYGON ((0 -5, 10 0, 10 -10, 0 -5))") is.valid(w) w <- vect("POLYGON ((0 -5, 10 0, 10 -10, 4 -2, 0 -5))") is.valid(w) is.valid(w, TRUE) plot(w) points(cbind(4.54, -2.72), cex=2, col="red") e <- ext(0, 1, 0, 1) is.valid(e) ee <- ext(0, 0, 0, 0) is.valid(ee)
Compute k-means clusters for a SpatRaster. For large SpatRasters (with ncell(x) > maxcell
) this is done in two steps. First a sample of the cells is used to compute the cluster centers. Then each cell is assigned to a cluster by computing the distance to these centers.
## S4 method for signature 'SpatRaster' k_means(x, centers=3, ..., maxcell=1000000, filename="", overwrite=FALSE, wopt=list())
## S4 method for signature 'SpatRaster' k_means(x, centers=3, ..., maxcell=1000000, filename="", overwrite=FALSE, wopt=list())
x |
SpatRaster |
centers |
either the number of clusters, or a set of initial (distinct) cluster centres. If a number, a random set of (distinct) cells in |
... |
additional arguments passed to |
maxcell |
positive integer. The size of the regular sample used if it is smaller than |
filename |
character. Output filename (ignored if |
overwrite |
logical. If |
wopt |
list with additional arguments for writing files as in |
SpatRaster
f <- system.file("ex/logo.tif", package = "terra") r <- rast(f) km <- k_means(r, centers=5) km
f <- system.file("ex/logo.tif", package = "terra") r <- rast(f) km <- k_means(r, centers=5) km
Apply a function to a SpatRaster, using layers as arguments.
The number of arguments in function fun
must match the number of layers in the SpatRaster (or the number of sub-datasets in the SpatRasterDataset). For example, if you want to multiply two layers, you could use this function: fun=function(x,y){return(x*y)}
percentage: fun=function(x,y){return(100 * x / y)}
. If you combine three layers you could use fun=function(x,y,z){return((x + y) * z)}
Before you use the function, test it to make sure that it is vectorized. That is, it should work for vectors longer than one, not only for single numbers. Or if the input SpatRaster(s) have multiple layers, it should work for a matrix (multiple cells) of input data (or matrices in the case of a SpatRasterDataSet). The function must return the same number of elements as its input vectors, or multiples of that. Also make sure that the function is NA
-proof: it should returns the same number of values when some or all input values are NA
. And the function must return a vector or a matrix, not a data.frame
. To test it, run it with do.call(fun, data)
(see examples).
Use app
for summarize functions such as sum
, that take any number of arguments; and tapp
to do so for groups of layers.
## S4 method for signature 'SpatRaster' lapp(x, fun, ..., usenames=FALSE, cores=1, filename="", overwrite=FALSE, wopt=list()) ## S4 method for signature 'SpatRasterDataset' lapp(x, fun, ..., usenames=FALSE, recycle=FALSE, filename="", overwrite=FALSE, wopt=list())
## S4 method for signature 'SpatRaster' lapp(x, fun, ..., usenames=FALSE, cores=1, filename="", overwrite=FALSE, wopt=list()) ## S4 method for signature 'SpatRasterDataset' lapp(x, fun, ..., usenames=FALSE, recycle=FALSE, filename="", overwrite=FALSE, wopt=list())
x |
SpatRaster or SpatRasterDataset |
fun |
a function that takes a vector and can be applied to each cell of |
... |
additional arguments to be passed to |
usenames |
logical. Use the layer names (or dataset names if |
cores |
positive integer. If |
recycle |
logical. Recycle layers to match the subdataset with the largest number of layers |
filename |
character. Output filename |
overwrite |
logical. If |
wopt |
list with named options for writing files as in |
SpatRaster
Use sapp
or lapply
to apply a function that takes a SpatRaster as argument to each layer of a SpatRaster (that is rarely necessary).
s <- rast(system.file("ex/logo.tif", package="terra")) + 1 ss <- s[[2:1]] fvi <- function(x, y){ (x - y ) / (x + y) } # test the function data <- list(c(1:5,NA), 6:1) do.call(fvi, data) x <- lapp(ss, fun=fvi ) # which is the same as supplying the layers to "fun" # in some cases this will be much faster y <- fvi(s[[2]], s[[1]]) f2 <- function(x, y, z){ (z - y + 1) / (x + y + 1) } p1 <- lapp(s, fun=f2 ) p2 <- lapp(s[[1:2]], f2, z=200) # the usenames argument fvi2 <- function(red, green){ (red - green ) / (red + green) } names(s) x1 <- lapp(s[[1:2]], fvi2, usenames=TRUE) x2 <- lapp(s[[2:1]], fvi2, usenames=TRUE) # x1 and x2 are the same, despite the change in the order of the layers # x4 is also the same, but x3 is not x3 <- lapp(s[[2:1]], fvi2, usenames=FALSE) x4 <- lapp(s, fvi2, usenames=TRUE) # while this would fail because # there are too many layers in s # x5 <- lapp(s, fvi2, usenames=FALSE) pairs(c(x1, x2, x3, x4)) ## SpatRasterDataset x <- sds(s, s[[1]]+50) fun <- function(x, y) { x/y } # test "fun" data <- list(matrix(1:9, ncol=3), matrix(9:1, ncol=3)) do.call(fun, data) lapp(x, fun, recycle=TRUE) # the same, more concisely z <- s / (s[[1]]+50)
s <- rast(system.file("ex/logo.tif", package="terra")) + 1 ss <- s[[2:1]] fvi <- function(x, y){ (x - y ) / (x + y) } # test the function data <- list(c(1:5,NA), 6:1) do.call(fvi, data) x <- lapp(ss, fun=fvi ) # which is the same as supplying the layers to "fun" # in some cases this will be much faster y <- fvi(s[[2]], s[[1]]) f2 <- function(x, y, z){ (z - y + 1) / (x + y + 1) } p1 <- lapp(s, fun=f2 ) p2 <- lapp(s[[1:2]], f2, z=200) # the usenames argument fvi2 <- function(red, green){ (red - green ) / (red + green) } names(s) x1 <- lapp(s[[1:2]], fvi2, usenames=TRUE) x2 <- lapp(s[[2:1]], fvi2, usenames=TRUE) # x1 and x2 are the same, despite the change in the order of the layers # x4 is also the same, but x3 is not x3 <- lapp(s[[2:1]], fvi2, usenames=FALSE) x4 <- lapp(s, fvi2, usenames=TRUE) # while this would fail because # there are too many layers in s # x5 <- lapp(s, fvi2, usenames=FALSE) pairs(c(x1, x2, x3, x4)) ## SpatRasterDataset x <- sds(s, s[[1]]+50) fun <- function(x, y) { x/y } # test "fun" data <- list(matrix(1:9, ncol=3), matrix(9:1, ncol=3)) do.call(fun, data) lapp(x, fun, recycle=TRUE) # the same, more concisely z <- s / (s[[1]]+50)
Compute correlation, (weighted) covariance, or similar summary statistics that compare the values of all pairs of the layers of a SpatRaster.
## S4 method for signature 'SpatRaster' layerCor(x, fun, w, asSample=TRUE, use="everything", maxcell=Inf, ...)
## S4 method for signature 'SpatRaster' layerCor(x, fun, w, asSample=TRUE, use="everything", maxcell=Inf, ...)
x |
SpatRaster |
fun |
character. The statistic to compute: either "cov" (covariance), "weighted.cov" (weighted covariance), or "cor" (pearson correlation coefficient) or your own function that takes two vectors as argument to compute a single number |
w |
SpatRaster with the weights to compute the weighted covariance. It should have a single layer and the same geometry as |
asSample |
logical. If |
use |
character. To decide how to handle missing values. This must be (an abbreviation of) one of "everything", "complete.obs", "pairwise.complete.obs", "masked.complete". With "pairwise.complete.obs", the value for a pair of layers is computed for all cells that are not |
maxcell |
positive integer. The maximum number of cells to be used. If this is smaller than ncell(x), a regular sample of |
... |
additional arguments for |
If fun
is one of the three standard statistics, you get a list with three items: the
correlation or (weighted) covariance matrix, the (weighted) means, and the number of data cells in
each comparison. The means are also a matrix because they may depend on the combination of layers
if different cells have missing values and these are excluded from the computation. The rows of
the mean matrix represent the layer whose (weighted) mean is being calculated and the columns
represent the layer it is being paired with. Only cells with non-missing observations for both
layers are used in the calculation of the (weighted) mean. The diagonals of the mean and n
matrices are set to missing.
If fun
is a function, you get a single matrix.
For the weighted covariance:
Canty, M.J. and A.A. Nielsen, 2008. Automatic radiometric normalization of multitemporal satellite imagery with the iteratively re-weighted MAD transformation. Remote Sensing of Environment 112:1025-1036.
Nielsen, A.A., 2007. The regularized iteratively reweighted MAD method for change detection in multi- and hyperspectral data. IEEE Transactions on Image Processing 16(2):463-478.
b <- rast(system.file("ex/logo.tif", package="terra")) layerCor(b, "pearson") layerCor(b, "cov") # weigh by column number w <- init(b, fun="col") layerCor(b, "weighted.cov", w=w)
b <- rast(system.file("ex/logo.tif", package="terra")) layerCor(b, "pearson") layerCor(b, "cov") # weigh by column number w <- init(b, fun="col") layerCor(b, "weighted.cov", w=w)
Get the linear units of the coordinate reference system (crs) of a SpatRaster or SpatVector expressed in m. The value returned is used internally to transform area and perimeter measures to meters. The value returned for longitude/latitude crs is zero.
## S4 method for signature 'SpatRaster' linearUnits(x) ## S4 method for signature 'SpatVector' linearUnits(x)
## S4 method for signature 'SpatRaster' linearUnits(x) ## S4 method for signature 'SpatVector' linearUnits(x)
x |
SpatRaster or SpatVector |
numeric (meter)
x <- rast() crs(x) <- "" linearUnits(x) crs(x) <- "+proj=longlat +datum=WGS84" linearUnits(x) crs(x) <- "+proj=utm +zone=1 +units=cm" linearUnits(x) crs(x) <- "+proj=utm +zone=1 +units=km" linearUnits(x) crs(x) <- "+proj=utm +zone=1 +units=us-ft" linearUnits(x)
x <- rast() crs(x) <- "" linearUnits(x) crs(x) <- "+proj=longlat +datum=WGS84" linearUnits(x) crs(x) <- "+proj=utm +zone=1 +units=cm" linearUnits(x) crs(x) <- "+proj=utm +zone=1 +units=km" linearUnits(x) crs(x) <- "+proj=utm +zone=1 +units=us-ft" linearUnits(x)
Add a vector geometries to a plot (map) with points
, lines
, or polys
.
These are simpler alternatives for plot(x, add=TRUE)
These methods also work for a small(!) SpatRaster. Only cells that are not NA in the first layer are used.
## S4 method for signature 'SpatVector' points(x, col, cex=0.7, pch=16, alpha=1, ...) ## S4 method for signature 'SpatVector' lines(x, y=NULL, col, lwd=1, lty=1, arrows=FALSE, alpha=1, ...) ## S4 method for signature 'SpatVector' polys(x, col, border="black", lwd=1, lty=1, alpha=1, ...) ## S4 method for signature 'SpatRaster' points(x, ...) ## S4 method for signature 'SpatRaster' lines(x, mx=10000, ...) ## S4 method for signature 'SpatRaster' polys(x, mx=10000, dissolve=TRUE, ...) ## S4 method for signature 'SpatExtent' points(x, col="black", alpha=1, ...) ## S4 method for signature 'SpatExtent' lines(x, col="black", alpha=1, ...) ## S4 method for signature 'SpatExtent' polys(x, col, alpha=1, ...)
## S4 method for signature 'SpatVector' points(x, col, cex=0.7, pch=16, alpha=1, ...) ## S4 method for signature 'SpatVector' lines(x, y=NULL, col, lwd=1, lty=1, arrows=FALSE, alpha=1, ...) ## S4 method for signature 'SpatVector' polys(x, col, border="black", lwd=1, lty=1, alpha=1, ...) ## S4 method for signature 'SpatRaster' points(x, ...) ## S4 method for signature 'SpatRaster' lines(x, mx=10000, ...) ## S4 method for signature 'SpatRaster' polys(x, mx=10000, dissolve=TRUE, ...) ## S4 method for signature 'SpatExtent' points(x, col="black", alpha=1, ...) ## S4 method for signature 'SpatExtent' lines(x, col="black", alpha=1, ...) ## S4 method for signature 'SpatExtent' polys(x, col, alpha=1, ...)
x |
SpatVector or SpatExtent |
y |
missing or SpatVector. If both |
col |
character. Colors |
border |
character. color(s) of the polygon borders. Use |
cex |
numeric. point size magnifier. See |
pch |
positive integer, point type. See |
alpha |
number between 0 and 1 to set transparency |
lwd |
numeric, line-width. See |
lty |
positive integer, line type. See |
arrows |
logical. If |
mx |
positive number. If the number of cells of SpatRaster |
dissolve |
logical. Should boundaries between cells with the same value be removed? |
... |
additional graphical arguments such as |
f <- system.file("ex/lux.shp", package="terra") v <- vect(f) r <- rast(v) values(r) <- 1:ncell(r) plot(r) lines(v) points(v)
f <- system.file("ex/lux.shp", package="terra") v <- vect(f) r <- rast(v) values(r) <- 1:ncell(r) plot(r) lines(v) points(v)
Divide a SpatRaster into "tiles". The cells of another SpatRaster (normally with a much lower resolution) or a SpatVector with polygon geometry can be used to define the tiles. You can also provide one or two numbers to indicate the number of rows and columns per tile.
getTileExtents
returns the extents of the (virtual) tiles, while makeTiles
creates files for the tiles and returns their filenames.
## S4 method for signature 'SpatRaster' makeTiles(x, y, filename="tile_.tif", extend=FALSE, na.rm=FALSE, buffer=0, overwrite=FALSE, ...) ## S4 method for signature 'SpatRaster' getTileExtents(x, y, extend=FALSE, buffer=0)
## S4 method for signature 'SpatRaster' makeTiles(x, y, filename="tile_.tif", extend=FALSE, na.rm=FALSE, buffer=0, overwrite=FALSE, ...) ## S4 method for signature 'SpatRaster' getTileExtents(x, y, extend=FALSE, buffer=0)
x |
SpatRaster |
y |
SpatRaster or SpatVector defining the zones; or numeric specifying the number of rows and columns for each zone (1 or 2 numbers if the number of rows and columns is not the same) |
filename |
character. Output filename template. Filenames will be altered by adding the tile number for each tile |
extend |
logical. If |
na.rm |
logical. If |
buffer |
integer. The number of additional rows and columns added to each tile. Can be a single number, or two numbers to specify a separate number of rows and columns. This allows for creating overlapping tiles that can be used for computing spatial context dependent values with e.g. |
overwrite |
logical. If |
... |
additional arguments for writing files as in |
character (filenames) or matrix (extents)
vrt
to create a virtual raster from tiles and crop
for sub-setting arbitrary parts of a SpatRaster.
r <- rast(ncols=100, nrows=100) values(r) <- 1:ncell(r) x <- rast(ncols=2, nrows=2) getTileExtents(r, x) getTileExtents(r, x, buffer=3) filename <- paste0(tempfile(), "_.tif") ff <- makeTiles(r, x, filename) ff vrt(ff)
r <- rast(ncols=100, nrows=100) values(r) <- 1:ncell(r) x <- rast(ncols=2, nrows=2) getTileExtents(r, x) getTileExtents(r, x, buffer=3) filename <- paste0(tempfile(), "_.tif") ff <- makeTiles(r, x, filename) ff vrt(ff)
Create a VRT header file for a "flat binary" raster file that needs a header file to be able to read it, but does not have it.
makeVRT(filename, nrow, ncol, nlyr=1, extent, xmin, ymin, xres, yres=xres, xycenter=TRUE, crs="+proj=longlat", lyrnms="", datatype, NAflag=NA, bandorder="BIL", byteorder="LSB", toptobottom=TRUE, offset=0, scale=1)
makeVRT(filename, nrow, ncol, nlyr=1, extent, xmin, ymin, xres, yres=xres, xycenter=TRUE, crs="+proj=longlat", lyrnms="", datatype, NAflag=NA, bandorder="BIL", byteorder="LSB", toptobottom=TRUE, offset=0, scale=1)
filename |
character. raster filename (without the ".vrt" extension) |
nrow |
positive integer, the number of rows |
ncol |
positive integer, the number of columns |
nlyr |
positive integer, the number of layers |
extent |
SpatExtent or missing |
xmin |
numeric. minimum x coordinate (only used if |
ymin |
numeric. minimum y coordinate (only used if |
xres |
positive number. x resolution |
yres |
positive number. y resolution) |
xycenter |
logical. If |
crs |
character. Coordinate reference system description |
lyrnms |
character. Layer names |
datatype |
character. One of "INT2S", "INT4S", "INT1U", "INT2U", "INT4U", "FLT4S", "FLT8S". If missing, this is guessed from the file size (INT1U for 1 byte per value, INT2S for 2 bytes and FLT4S for 4 bytes per value). This may be wrong because, for example, 2 bytes per value may in fact be INT2U (with the U for unsigned) values |
NAflag |
numeric. The value used as the "NA flag" |
bandorder |
character. One of "BIL", "BIP", or "BSQ". That is Band Interleaved by Line, or by Pixel, or Band SeQuential |
byteorder |
character. One of "LSB", "MSB". "MSB" is common for files generated on Linux systems, whereas "LSB" is common for files generated on windows |
toptobottom |
logical. If |
offset |
numeric. offset to be applied |
scale |
numeric. scale to be applied |
character (.VRT filename)
vrt
to create a vrt for a collection of raster tiles
Helper function for creating custom map elements that are aligned with the axes of a map (base plot created with a SpatRaster and/or SpatVector). For example, you may need to know the coordinates for the upper-left corner of a map to add some information there.
Unlike the standard base plot, terra keeps the axis aligned with the data. For that reason you cannot use par()$usr
to get these coordinates.
The coordinates returned by this function are used in, for example, add_legend
such that a legend can be automatically placed in the a particular corner.
This function only returns meaningful results of the active plot (canvas) was create with a call to plot
with a SpatRaster or SpatVector as first argument.
map_extent()
map_extent()
r <- rast(xmin=0, xmax=10, ymin=0, ymax=10, res=1, vals=1:100) plot(r) map_extent() par()$usr
r <- rast(xmin=0, xmax=10, ymin=0, ymax=10, res=1, vals=1:100) plot(r) map_extent() par()$usr
Get a color palette for mapping. These palettes were copied from GRASS.
map.pal(name, n=50, ...)
map.pal(name, n=50, ...)
name |
character (name of a palette, see Details), or missing (to get the available names) |
n |
numeric. The number of colors |
... |
additional arguments that are passed to |
Name | Description |
aspect | aspect oriented grey colors |
bcyr | blue through cyan through yellow to red |
bgyr | blue through green through yellow to red |
blues | white to blue |
byg | blue through yellow to green |
byr | blue through yellow to red |
curvature | for terrain curvatures |
differences | differences oriented colors |
elevation | maps relative ranges of raster values to elevation color ramp |
grass | GRASS GIS green (perceptually uniform) |
greens | white to green |
grey | grey scale |
grey.eq | histogram-equalized grey scale |
grey.log | histogram logarithmic transformed grey scale |
gyr | green through yellow to red |
haxby | relative colors for bathymetry or topography |
inferno | perceptually uniform sequential color table inferno |
magma | perceptually uniform sequential color table magma |
oranges | white to orange |
plasma | perceptually uniform sequential color table plasma |
rainbow | rainbow color table |
ramp | color ramp |
random | random color table |
reds | white to red |
roygbiv | |
rstcurv | terrain curvature |
ryb | red through yellow to blue |
ryg | red through yellow to green |
sepia | yellowish-brown through to white |
viridis | perceptually uniform sequential color table viridis |
water | water depth |
wave | color wave |
none
map.pal("elevation", 10) r <- rast(system.file("ex/elev.tif", package="terra")) plot(r, col=map.pal("elevation")) map.pal()
map.pal("elevation", 10) r <- rast(system.file("ex/elev.tif", package="terra")) plot(r, col=map.pal("elevation")) map.pal()
If x
is a SpatRaster
:
Create a new SpatRaster that has the same values as SpatRaster x
, except for the cells that are NA
(or other maskvalue
) in another SpatRaster (the 'mask'), or the cells that are not covered by a SpatVector or SpatExtent. These cells become NA
(or another updatevalue
).
If x
is a SpatVector or SpatExtent:
Select geometries of x
that intersect, or not intersect, with the geometries of y
.
## S4 method for signature 'SpatRaster,SpatRaster' mask(x, mask, inverse=FALSE, maskvalues=NA, updatevalue=NA, filename="", ...) ## S4 method for signature 'SpatRaster,SpatVector' mask(x, mask, inverse=FALSE, updatevalue=NA, touches=TRUE, filename="", ...) ## S4 method for signature 'SpatRaster,SpatExtent' mask(x, mask, inverse=FALSE, updatevalue=NA, touches=TRUE, filename="", ...) ## S4 method for signature 'SpatVector,SpatVector' mask(x, mask, inverse=FALSE) ## S4 method for signature 'SpatVector,SpatExtent' mask(x, mask, inverse=FALSE)
## S4 method for signature 'SpatRaster,SpatRaster' mask(x, mask, inverse=FALSE, maskvalues=NA, updatevalue=NA, filename="", ...) ## S4 method for signature 'SpatRaster,SpatVector' mask(x, mask, inverse=FALSE, updatevalue=NA, touches=TRUE, filename="", ...) ## S4 method for signature 'SpatRaster,SpatExtent' mask(x, mask, inverse=FALSE, updatevalue=NA, touches=TRUE, filename="", ...) ## S4 method for signature 'SpatVector,SpatVector' mask(x, mask, inverse=FALSE) ## S4 method for signature 'SpatVector,SpatExtent' mask(x, mask, inverse=FALSE)
x |
SpatRaster or SpatVector |
mask |
SpatRaster or SpatVector |
inverse |
logical. If |
maskvalues |
numeric. The value(s) in |
updatevalue |
numeric. The value that masked cells should become (if they are not |
touches |
logical. If |
filename |
character. Output filename |
... |
additional arguments for writing files as in |
SpatRaster
f <- system.file("ex/elev.tif", package="terra") r <- rast(f) msk <- ifel(r < 400, NA, 1) m <- mask(r, msk) f <- system.file("ex/lux.shp", package="terra") v <- vect(f)[1,] mv1 <- mask(r, v) mv2 <- crop(r, v, mask=TRUE)
f <- system.file("ex/elev.tif", package="terra") r <- rast(f) msk <- ifel(r < 400, NA, 1) m <- mask(r, msk) f <- system.file("ex/lux.shp", package="terra") v <- vect(f)[1,] mv1 <- mask(r, v) mv2 <- crop(r, v, mask=TRUE)
match
returns a SpatRaster with the position of the matched values. The cell values are the index of the table argument.
%in%
returns a 0/1 (FALSE/TRUE) SpatRaster indicating if the cells values were matched or not.
match(x, table, nomatch = NA_integer_, incomparables = NULL) x %in% table
match(x, table, nomatch = NA_integer_, incomparables = NULL) x %in% table
x |
SpatRaster |
table |
vector of the values to be matched against |
nomatch |
the value to be returned in the case when no match is found. Note that it is coerced to integer |
incomparables |
a vector of values that cannot be matched. Any value in x matching a value in this vector is assigned the nomatch value. For historical reasons, FALSE is equivalent to NULL |
SpatRaster
r <- rast(nrows=10, ncols=10) values(r) <- 1:100 m <- match(r, c(5:10, 50:55)) n <- r %in% c(5:10, 50:55)
r <- rast(nrows=10, ncols=10) values(r) <- 1:100 m <- match(r, c(5:10, 50:55)) n <- r %in% c(5:10, 50:55)
Standard mathematical methods for computations with SpatRasters. Computations are local (applied on a cell by cell basis). If multiple SpatRasters are used, these must have the same extent and resolution. These have been implemented:
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
Instead of directly calling these methods, you can also provide their name to the math
method. This is useful if you want to provide an output filename.
The following methods have been implemented for SpatExtent
: round, floor, ceiling
round
has also been implemented for SpatVector
, to round the coordinates of the geometries.
## S4 method for signature 'SpatRaster' sqrt(x) ## S4 method for signature 'SpatRaster' log(x, base=exp(1)) ## S4 method for signature 'SpatRaster' round(x, digits=0) ## S4 method for signature 'SpatRaster' math(x, fun, digits=0, filename="", overwrite=FALSE, ...) ## S4 method for signature 'SpatVector' round(x, digits=4) ## S4 method for signature 'SpatRaster' cumsum(x)
## S4 method for signature 'SpatRaster' sqrt(x) ## S4 method for signature 'SpatRaster' log(x, base=exp(1)) ## S4 method for signature 'SpatRaster' round(x, digits=0) ## S4 method for signature 'SpatRaster' math(x, fun, digits=0, filename="", overwrite=FALSE, ...) ## S4 method for signature 'SpatVector' round(x, digits=4) ## S4 method for signature 'SpatRaster' cumsum(x)
x |
SpatRaster |
base |
a positive or complex number: the base with respect to which logarithms are computed |
digits |
Number of digits for rounding |
fun |
character. Math function name |
filename |
character. Output filename |
overwrite |
logical. If |
... |
additional arguments for writing files as in |
SpatRaster or SpatExtent
See app
to use mathematical functions not implemented by the package, and Arith-methods
for arithmetical operations. Use roll
for rolling functions.
r1 <- rast(ncols=10, nrows=10) v <- runif(ncell(r1)) v[10:20] <- NA values(r1) <- v r2 <- rast(r1) values(r2) <- 1:ncell(r2) / ncell(r2) r <- c(r1, r2) s <- sqrt(r) # same as math(r, "sqrt") round(s, 1) cumsum(r)
r1 <- rast(ncols=10, nrows=10) v <- runif(ncell(r1)) v[10:20] <- NA values(r1) <- v r2 <- rast(r1) values(r2) <- 1:ncell(r2) / ncell(r2) r <- c(r1, r2) s <- sqrt(r) # same as math(r, "sqrt") round(s, 1) cumsum(r)
mem_info
prints the amount of RAM that is required and available to process a SpatRaster.
free_RAM
returns the amount of RAM that is available
mem_info(x, n=1) free_RAM()
mem_info(x, n=1) free_RAM()
x |
SpatRaster |
n |
positive integer. The number of copies of |
free_RAM returns the amount of available RAM in kilobytes
mem_info(rast()) free_RAM()
mem_info(rast()) free_RAM()
Merge multiple SpatRasters to create a new SpatRaster with a larger spatial extent. The SpatRasters must have the same origin and spatial resolution. In areas where the SpatRasters overlap, the values of the SpatRaster that is first in the sequence of arguments (or in the SpatRasterCollection) will be retained (unless first=FALSE
). Cells that are NA
are ignored unless na.rm=FALSE
There is also a method for merging SpatVector with a data.frame; that is, to join the data.frame to the attribute table of the SpatVector.
## S4 method for signature 'SpatRaster,SpatRaster' merge(x, y, ..., first=TRUE, na.rm=TRUE, filename="", overwrite=FALSE, wopt=list()) ## S4 method for signature 'SpatRasterCollection,missing' merge(x, first=TRUE, na.rm=TRUE, filename="", ...) ## S4 method for signature 'SpatVector,data.frame' merge(x, y, ...)
## S4 method for signature 'SpatRaster,SpatRaster' merge(x, y, ..., first=TRUE, na.rm=TRUE, filename="", overwrite=FALSE, wopt=list()) ## S4 method for signature 'SpatRasterCollection,missing' merge(x, first=TRUE, na.rm=TRUE, filename="", ...) ## S4 method for signature 'SpatVector,data.frame' merge(x, y, ...)
x |
SpatRaster, SpatRasterCollection, or SpatVector |
y |
missing if |
... |
if |
first |
logical. If |
na.rm |
logical. If |
filename |
character. Output filename |
overwrite |
logical. If |
wopt |
list with named options for writing files as in |
SpatRaster or SpatVector
Combining tiles with vrt
may be more efficient than using merge
. See mosaic
for averaging overlapping regions.
See classify
to merge a SpatRaster
and a data.frame
and union
to combine SpatExtent objects.
x <- rast(xmin=-110, xmax=-80, ymin=40, ymax=70, res=1, vals=1) y <- rast(xmin=-85, xmax=-55, ymax=60, ymin=30, res=1, vals=2) z <- rast(xmin=-60, xmax=-30, ymax=50, ymin=20, res=1, vals=3) m1 <- merge(x, y, z) m2 <- merge(z, y, x) m3 <- merge(y, x, z) # if you have many SpatRasters, it may be convenient # to make a SpatRasterCollection rlist <- list(x, y, z) rsrc <- sprc(rlist) m <- merge(rsrc) ## SpatVector with data.frame f <- system.file("ex/lux.shp", package="terra") p <- vect(f) dfr <- data.frame(District=p$NAME_1, Canton=p$NAME_2, Value=round(runif(length(p), 100, 1000))) dfr <- dfr[1:5, ] pm <- merge(p, dfr, all.x=TRUE, by.x=c('NAME_1', 'NAME_2'), by.y=c('District', 'Canton')) pm values(pm)
x <- rast(xmin=-110, xmax=-80, ymin=40, ymax=70, res=1, vals=1) y <- rast(xmin=-85, xmax=-55, ymax=60, ymin=30, res=1, vals=2) z <- rast(xmin=-60, xmax=-30, ymax=50, ymin=20, res=1, vals=3) m1 <- merge(x, y, z) m2 <- merge(z, y, x) m3 <- merge(y, x, z) # if you have many SpatRasters, it may be convenient # to make a SpatRasterCollection rlist <- list(x, y, z) rsrc <- sprc(rlist) m <- merge(rsrc) ## SpatVector with data.frame f <- system.file("ex/lux.shp", package="terra") p <- vect(f) dfr <- data.frame(District=p$NAME_1, Canton=p$NAME_2, Value=round(runif(length(p), 100, 1000))) dfr <- dfr[1:5, ] pm <- merge(p, dfr, all.x=TRUE, by.x=c('NAME_1', 'NAME_2'), by.y=c('District', 'Canton')) pm values(pm)
Combine SpatRasters with partly overlapping time-stamps to create a single time series. If there is no overlap between the SpatRasters there is no point in using this function (use c
instead).
Also note that time gaps are not filled. You can use fillTime
to do that.
## S4 method for signature 'SpatRasterDataset' mergeTime(x, fun=mean, filename="", ...)
## S4 method for signature 'SpatRasterDataset' mergeTime(x, fun=mean, filename="", ...)
x |
SpatRasterDataset |
fun |
A function that reduces a vector to a single number, such as |
filename |
character. Output filename |
... |
list with named options for writing files as in |
SpatRaster
r <- rast(system.file("ex/logo.tif", package="terra")) s1 <- c(r, r) time(s1) <- as.Date("2001-01-01") + 0:5 s1 <- s1/10 time(s1) <- as.Date("2001-01-07") + 0:5 s2 <- s1*10 time(s2) <- as.Date("2001-01-05") + 0:5 x <- sds(s1, s1, s2) m <- mergeTime(x, mean)
r <- rast(system.file("ex/logo.tif", package="terra")) s1 <- c(r, r) time(s1) <- as.Date("2001-01-01") + 0:5 s1 <- s1/10 time(s1) <- as.Date("2001-01-07") + 0:5 s2 <- s1*10 time(s2) <- as.Date("2001-01-05") + 0:5 x <- sds(s1, s1, s2) m <- mergeTime(x, mean)
Get metadata associated with the sources or layers of a SpatRaster
## S4 method for signature 'SpatRaster' meta(x, layers=FALSE)
## S4 method for signature 'SpatRaster' meta(x, layers=FALSE)
x |
SpatRaster |
layers |
logical. Should the layer level metadata be returned? |
list
You can set arbitrary metadata to a SpatRaster using "name=value" tags.
## S4 replacement method for signature 'SpatRaster' metags(x, layer=NULL)<-value ## S4 method for signature 'SpatRaster' metags(x, layer=NULL, name=NULL)
## S4 replacement method for signature 'SpatRaster' metags(x, layer=NULL)<-value ## S4 method for signature 'SpatRaster' metags(x, layer=NULL, name=NULL)
x |
SpatRaster |
layer |
NULL or positive integer. If the value is NULL, the tags assigned or returned are for the SpatRaster. Otherwise for the layer number(s) |
name |
character |
value |
character of "name=value" or two-column matrix |
SpatRaster (metags<-
), or named character (metags
)
r <- rast(ncol=5, nrow=5) m <- cbind(c("one", "two", "three"), c("ABC", "123", "hello")) metags(r) <- m metags(r) metags(r) <- c("another_tag=another_value", "one more=this value") metags(r) metags(r) <- c(another_tag="44", `one more`="that value") metags(r) metags(r, name="two") # remove a tag metags(r) <- cbind("one", "") metags(r) <- "two=" metags(r) # remove all metags metags(r) <- NULL metags(r)
r <- rast(ncol=5, nrow=5) m <- cbind(c("one", "two", "three"), c("ABC", "123", "hello")) metags(r) <- m metags(r) metags(r) <- c("another_tag=another_value", "one more=this value") metags(r) metags(r) <- c(another_tag="44", `one more`="that value") metags(r) metags(r, name="two") # remove a tag metags(r) <- cbind("one", "") metags(r) <- "two=" metags(r) # remove all metags metags(r) <- NULL metags(r)
Compute the mode for each cell across the layers of a SpatRaster. The mode, or modal value, is the most frequent value in a set of values.
## S4 method for signature 'SpatRaster' modal(x, ..., ties="first", na.rm=FALSE, filename="", overwrite=FALSE, wopt=list())
## S4 method for signature 'SpatRaster' modal(x, ..., ties="first", na.rm=FALSE, filename="", overwrite=FALSE, wopt=list())
x |
SpatRaster |
... |
additional argument of the same type as |
ties |
character. Indicates how to treat ties. Either "random", "lowest", "highest", "first", or "NA" |
na.rm |
logical. If |
filename |
character. Output filename |
overwrite |
logical. If |
wopt |
list with named options for writing files as in |
SpatRaster
r <- rast(system.file("ex/logo.tif", package="terra")) r <- c(r/2, r, r*2) m <- modal(r)
r <- rast(system.file("ex/logo.tif", package="terra")) r <- c(r/2, r, r*2) m <- modal(r)
Combine adjacent and (partly) overlapping SpatRasters to form a single new SpatRaster. Values in overlapping cells are averaged (by default) or can be computed with another function.
The SpatRasters must have the same origin and spatial resolution.
This method is similar to the simpler, but much faster, merge
method.
## S4 method for signature 'SpatRaster,SpatRaster' mosaic(x, y, ..., fun="mean", filename="", overwrite=FALSE, wopt=list()) ## S4 method for signature 'SpatRasterCollection,missing' mosaic(x, fun="mean", filename="", ...)
## S4 method for signature 'SpatRaster,SpatRaster' mosaic(x, y, ..., fun="mean", filename="", overwrite=FALSE, wopt=list()) ## S4 method for signature 'SpatRasterCollection,missing' mosaic(x, fun="mean", filename="", ...)
x |
SpatRaster |
y |
object of same class as |
... |
additional SpatRasters |
fun |
character. One of "mean", "median", "min", "max", "modal", "sum", "first", "last" |
filename |
character. Output filename |
overwrite |
logical. If |
wopt |
list with named options for writing files as in |
SpatRaster
x <- rast(xmin=-110, xmax=-60, ymin=40, ymax=70, res=1, vals=1) y <- rast(xmin=-95, xmax=-45, ymax=60, ymin=30, res=1, vals=2) z <- rast(xmin=-80, xmax=-30, ymax=50, ymin=20, res=1, vals=3) m1 <- mosaic(x, y, z) m2 <- mosaic(z, y, x) # with many SpatRasters, make a SpatRasterCollection from a list rlist <- list(x, y, z) rsrc <- sprc(rlist) m <- mosaic(rsrc)
x <- rast(xmin=-110, xmax=-60, ymin=40, ymax=70, res=1, vals=1) y <- rast(xmin=-95, xmax=-45, ymax=60, ymin=30, res=1, vals=2) z <- rast(xmin=-80, xmax=-30, ymax=50, ymin=20, res=1, vals=3) m1 <- mosaic(x, y, z) m2 <- mosaic(z, y, x) # with many SpatRasters, make a SpatRasterCollection from a list rlist <- list(x, y, z) rsrc <- sprc(rlist) m <- mosaic(rsrc)
Find geometries that are NA; or remove geometries and/or records that are NA
.
## S4 method for signature 'SpatVector' is.na(x) ## S4 method for signature 'SpatVector' na.omit(object, field=NA, geom=FALSE)
## S4 method for signature 'SpatVector' is.na(x) ## S4 method for signature 'SpatVector' na.omit(object, field=NA, geom=FALSE)
x |
SpatVector |
object |
SpatVector |
field |
character or NA. If |
geom |
logical. If |
SpatVector
f <- system.file("ex/lux.shp", package="terra") v <- vect(f) v$test <- c(1,2,NA) nrow(v) x <- na.omit(v, "test") nrow(x)
f <- system.file("ex/lux.shp", package="terra") v <- vect(f) v$test <- c(1,2,NA) nrow(v) x <- na.omit(v, "test") nrow(x)
The main purpose of this method is to allow correct reading of a SpatRaster that is based on a file that has an incorrect NA flag. The file is not changed, but flagged value is set to NA when values are read from the file ("lazy evaluation"). In contrast, if the values are in memory the change is made immediately.
To change values, it is generally better to use classify
## S4 method for signature 'SpatRaster' NAflag(x) ## S4 replacement method for signature 'SpatRaster' NAflag(x)<-value
## S4 method for signature 'SpatRaster' NAflag(x) ## S4 replacement method for signature 'SpatRaster' NAflag(x)<-value
x |
SpatRaster |
value |
numeric. The value to be interpreted as NA; set this before reading the values from the file. This can be a single value, or multiple values, one for each data source (file / subdataset) |
none or numeric
s <- rast(system.file("ex/logo.tif", package="terra"))[[1]] NAflag(s) <- 255 plot(s) NAflag(s)
s <- rast(system.file("ex/logo.tif", package="terra"))[[1]] NAflag(s) <- 255 plot(s) NAflag(s)
Get or set the names of the layers of a SpatRaster or the attributes of a SpatVector.
See set.names
for in-place setting of names.
## S4 method for signature 'SpatRaster' names(x) ## S4 replacement method for signature 'SpatRaster' names(x)<-value ## S4 method for signature 'SpatRasterDataset' names(x) ## S4 replacement method for signature 'SpatRasterDataset' names(x)<-value ## S4 method for signature 'SpatVector' names(x) ## S4 replacement method for signature 'SpatVector' names(x)<-value
## S4 method for signature 'SpatRaster' names(x) ## S4 replacement method for signature 'SpatRaster' names(x)<-value ## S4 method for signature 'SpatRasterDataset' names(x) ## S4 replacement method for signature 'SpatRasterDataset' names(x)<-value ## S4 method for signature 'SpatVector' names(x) ## S4 replacement method for signature 'SpatVector' names(x)<-value
x |
SpatRaster, SpatRasterDataset, or SpatVector |
value |
character (vector) |
character
terra enforces neither unique nor valid names. See make.unique
to create unique names and make.names
to make syntactically valid names.
s <- rast(ncols=5, nrows=5, nlyrs=3) nlyr(s) names(s) names(s) <- c("a", "b", "c") names(s) # SpatVector names f <- system.file("ex/lux.shp", package="terra") v <- vect(f) names(v) names(v) <- paste0(substr(names(v), 1, 2), "_", 1:ncol(v)) names(v)
s <- rast(ncols=5, nrows=5, nlyrs=3) nlyr(s) names(s) names(s) <- c("a", "b", "c") names(s) # SpatVector names f <- system.file("ex/lux.shp", package="terra") v <- vect(f) names(v) names(v) <- paste0(substr(names(v), 1, 2), "_", 1:ncol(v)) names(v)
Identify geometries that are near to each other. Either get the index of all geometries within a certain distance, or the k nearest neighbors, or (with nearest
) get the nearest points between two geometries.
## S4 method for signature 'SpatVector' nearby(x, y=NULL, distance=0, k=1, centroids=TRUE, symmetrical=TRUE) ## S4 method for signature 'SpatVector' nearest(x, y, pairs=FALSE, centroids=TRUE, lines=FALSE)
## S4 method for signature 'SpatVector' nearby(x, y=NULL, distance=0, k=1, centroids=TRUE, symmetrical=TRUE) ## S4 method for signature 'SpatVector' nearest(x, y, pairs=FALSE, centroids=TRUE, lines=FALSE)
x |
SpatVector |
y |
SpatVector or NULL |
distance |
numeric. maximum distance |
k |
positive integer. number of neighbors. Ignored if |
centroids |
logical. Should the centroids of polygons be used? |
symmetrical |
logical. If |
pairs |
logical. If |
lines |
logical. If |
matrix
f <- system.file("ex/lux.shp", package="terra") v <- vect(f) nearby(v, distance=12000)
f <- system.file("ex/lux.shp", package="terra") v <- vect(f) nearby(v, distance=12000)
Compute the number of immediate adjacent cells flowing into each cell
## S4 method for signature 'SpatRaster' NIDP(x, filename="",...)
## S4 method for signature 'SpatRaster' NIDP(x, filename="",...)
x |
SpatRaster with flow-direction. see |
filename |
character. Output filename |
... |
additional arguments for writing files as in |
NDIP is computed first to compute flow-accumulation with the algorithm by Zhou at al, 2019.
SpatRaster
Emanuele Cordano
Zhou, G., Wei, H. & Fu, S. A fast and simple algorithm for calculating flow accumulation matrices from raster digital elevation. Front. Earth Sci. 13, 317–326 (2019). https://doi.org/10.1007/s11707-018-0725-9 https://link.springer.com/article/10.1007/s11707-018-0725-9
elev1 <- array(NA,c(9,9)) elev2 <- elev1 dx <- 1 dy <- 1 for (r in 1:nrow(elev1)) { y <- (r-5)*dx for (c in 1:ncol(elev1)) { x <- (c-5)*dy elev1[r,c] <- 5*(x^2+y^2) elev2[r,c] <- 10+5*(abs(x))-0.001*y ### 5*(x^2+y^2) } } ## Elevation Raster elev1 <- rast(elev1) elev2 <- rast(elev2) t(array(elev1[],rev(dim(elev1)[1:2]))) t(array(elev2[],rev(dim(elev2)[1:2]))) plot(elev1) plot(elev2) ## Flow Direction Raster flowdir1<- terrain(elev1,v="flowdir") flowdir2<- terrain(elev2,v="flowdir") t(array(flowdir1[],rev(dim(flowdir1)[1:2]))) t(array(flowdir2[],rev(dim(flowdir2)[1:2]))) plot(flowdir1) plot(flowdir2) ## nidp1 <- NIDP((flowdir1)) nidp2 <- NIDP((flowdir2)) t(array(nidp1[],rev(dim(nidp1)[1:2]))) t(array(nidp2[],rev(dim(nidp2)[1:2]))) plot(nidp1) plot(nidp2)
elev1 <- array(NA,c(9,9)) elev2 <- elev1 dx <- 1 dy <- 1 for (r in 1:nrow(elev1)) { y <- (r-5)*dx for (c in 1:ncol(elev1)) { x <- (c-5)*dy elev1[r,c] <- 5*(x^2+y^2) elev2[r,c] <- 10+5*(abs(x))-0.001*y ### 5*(x^2+y^2) } } ## Elevation Raster elev1 <- rast(elev1) elev2 <- rast(elev2) t(array(elev1[],rev(dim(elev1)[1:2]))) t(array(elev2[],rev(dim(elev2)[1:2]))) plot(elev1) plot(elev2) ## Flow Direction Raster flowdir1<- terrain(elev1,v="flowdir") flowdir2<- terrain(elev2,v="flowdir") t(array(flowdir1[],rev(dim(flowdir1)[1:2]))) t(array(flowdir2[],rev(dim(flowdir2)[1:2]))) plot(flowdir1) plot(flowdir2) ## nidp1 <- NIDP((flowdir1)) nidp2 <- NIDP((flowdir2)) t(array(nidp1[],rev(dim(nidp1)[1:2]))) t(array(nidp2[],rev(dim(nidp2)[1:2]))) plot(nidp1) plot(nidp2)
Normalize the longitude of geometries, move them if they are outside of the -180 to 180 degrees range.
## S4 method for signature 'SpatVector' normalize.longitude(x)
## S4 method for signature 'SpatVector' normalize.longitude(x)
x |
SpatVector |
SpatVector
rotate for SpatRaster
p <- vect("POLYGON ((120 10, 230 75, 230 -75, 120 10))") normalize.longitude(p)
p <- vect("POLYGON ((120 10, 230 75, 230 -75, 120 10))") normalize.longitude(p)
Add a (North) arrow to a map
north(xy=NULL, type=1, label="N", angle=0, d, head=0.1, xpd=TRUE, ...)
north(xy=NULL, type=1, label="N", angle=0, d, head=0.1, xpd=TRUE, ...)
xy |
numeric. x and y coordinate to place the arrow. It can also be one of following character values: "bottomleft", "bottom", "bottomright", topleft", "top", "topright", "left", "right", or NULL |
type |
integer between 1 and 12, or a character (unicode) representation of a right pointing arrow such as |
label |
character, to be printed near the arrow |
angle |
numeric. The angle of the arrow in degrees |
d |
numeric. Distance covered by the arrow in plot coordinates. Only applies to |
head |
numeric. The size of the arrow "head", for |
xpd |
logical. If |
... |
graphical arguments to be passed to other methods |
none
f <- system.file("ex/meuse.tif", package="terra") r <- rast(f) plot(r) north() north(c(178550, 332500), d=250) ## Not run: f <- system.file("ex/elev.tif", package="terra") r <- rast(f) plot(r, type="interval") sbar(15, c(6.3, 50), type="bar", below="km", label=c(0,7.5,15), cex=.8) north(type=3, cex=.8) north(xy=c(6.7, 49.9), type=2, angle=45, label="NE") north(xy=c(6.6, 49.7), type=5, cex=1.25) north(xy=c(5.5, 49.6), type=9) north(d=.05, xy=c(5.5, 50), angle=180, label="S", lwd=2, col="blue") ## all arrows r <- rast(res=10) values(r) <- 1 plot(r, col="white", axes=FALSE, legend=FALSE, mar=c(0,0,0,0), reset=TRUE) for (i in 1:12) { x = -200+i*30 north(xy=cbind(x,30), type=i) text(x, -20, i, xpd=TRUE) } ## End(Not run)
f <- system.file("ex/meuse.tif", package="terra") r <- rast(f) plot(r) north() north(c(178550, 332500), d=250) ## Not run: f <- system.file("ex/elev.tif", package="terra") r <- rast(f) plot(r, type="interval") sbar(15, c(6.3, 50), type="bar", below="km", label=c(0,7.5,15), cex=.8) north(type=3, cex=.8) north(xy=c(6.7, 49.9), type=2, angle=45, label="NE") north(xy=c(6.6, 49.7), type=5, cex=1.25) north(xy=c(5.5, 49.6), type=9) north(d=.05, xy=c(5.5, 50), angle=180, label="S", lwd=2, col="blue") ## all arrows r <- rast(res=10) values(r) <- 1 plot(r, col="white", axes=FALSE, legend=FALSE, mar=c(0,0,0,0), reset=TRUE) for (i in 1:12) { x = -200+i*30 north(xy=cbind(x,30), type=i) text(x, -20, i, xpd=TRUE) } ## End(Not run)
Shortcut method to avoid the two-step !is.na(x)
## S4 method for signature 'SpatRaster' not.na(x, falseNA, filename="", ...)
## S4 method for signature 'SpatRaster' not.na(x, falseNA, filename="", ...)
x |
SpatRaster |
falseNA |
logical. Should the result be |
filename |
character. Output filename |
... |
additional arguments for writing files as in |
SpatRaster
r <- rast(ncols=10, nrows=10, vals=1) r[10:20] <- NA x <- not.na(r)
r <- rast(ncols=10, nrows=10, vals=1) r[10:20] <- NA x <- not.na(r)
Get or set general options.
terraOptions(..., print=TRUE)
terraOptions(..., print=TRUE)
... |
option names and values (see Details). Or missing, to get or show the current options |
print |
logical. If |
The following options are available.
memfrac - value between 0 and 0.9 (larger values give a warning). The fraction of RAM that may be used by the program.
memmin - if memory required is below this threshold (in GB), the memory is assumed to be available. Otherwise, terra checks if it is available.
memmax - the maximum amount of RAM (in GB) that terra is allowed to use when processing a raster dataset. Should be less than what is detected (see mem_info
), and higher values are ignored. Set it to a negative number or NA to not set this option. terraOptions
only shows the value of memmax
if it is set.
tempdir - directory where temporary files are written. The default what is returned by tempdir()
.
datatype - default data type. See writeRaster
todisk - logical. If TRUE
write all raster data to disk (temp file if no file name is specified). For debugging.
progress - non-negative integer. A progress bar is shown if the number of chunks in which the data is processed is larger than this number. No progress bar is shown if the value is zero
verbose - logical. If TRUE
debugging info is printed for some functions
list. Invisibly if print=TRUE
It is possible to set your own default options in "etc/.Rprofile.site" of your R installation like this
options(terra_default=list(tempdir="d:/temp", memfrac=.4))
But that may not be a good practice. It is clearer to set your favorite options at the beginning of each script.
terraOptions() terraOptions(memfrac=0.5, tempdir = "c:/temp") terraOptions(progress=10) terraOptions()
terraOptions() terraOptions(memfrac=0.5, tempdir = "c:/temp") terraOptions(progress=10) terraOptions()
Get or set the coordinates of the point of origin of a SpatRaster. This is the point closest to (0, 0) that you could get if you moved towards that point in steps of the x and y resolution.
## S4 method for signature 'SpatRaster' origin(x) ## S4 replacement method for signature 'SpatRaster' origin(x)<-value
## S4 method for signature 'SpatRaster' origin(x) ## S4 replacement method for signature 'SpatRaster' origin(x)<-value
x |
SpatRaster |
value |
numeric vector of length 1 or 2 |
A vector of two numbers (x and y coordinates)
r <- rast(xmin=-0.5, xmax = 9.5, ncols=10) origin(r) origin(r) <- c(0,0) r
r <- rast(xmin=-0.5, xmax = 9.5, ncols=10) origin(r) origin(r) <- c(0,0) r
Pair plots of layers in a SpatRaster. This is a wrapper around graphics function pairs
.
## S4 method for signature 'SpatRaster' pairs(x, hist=TRUE, cor=TRUE, use="pairwise.complete.obs", maxcells=100000, ...)
## S4 method for signature 'SpatRaster' pairs(x, hist=TRUE, cor=TRUE, use="pairwise.complete.obs", maxcells=100000, ...)
x |
SpatRaster |
hist |
logical. If TRUE a histogram of the values is shown on the diagonal |
cor |
logical. If TRUE the correlation coefficient is shown in the upper panels |
use |
argument passed to the |
maxcells |
integer. Number of pixels to sample from each layer of a large SpatRaster |
... |
additional arguments (graphical parameters) |
r <-rast(system.file("ex/elev.tif", package="terra")) s <- c(r, 1/r, sqrt(r)) names(s) <- c("elevation", "inverse", "sqrt") pairs(s) # to make indvidual histograms: hist(r) # or scatter plots: plot(s[[1]], s[[2]])
r <-rast(system.file("ex/elev.tif", package="terra")) s <- c(r, 1/r, sqrt(r)) names(s) <- c("elevation", "inverse", "sqrt") pairs(s) # to make indvidual histograms: hist(r) # or scatter plots: plot(s[[1]], s[[2]])
Show multiple maps that share a single legend.
## S4 method for signature 'SpatRaster' panel(x, main, loc.main="topleft", nc, nr, maxnl=16, maxcell=500000, box=FALSE, pax=list(), plg=list(), range=NULL, ...)
## S4 method for signature 'SpatRaster' panel(x, main, loc.main="topleft", nc, nr, maxnl=16, maxcell=500000, box=FALSE, pax=list(), plg=list(), range=NULL, ...)
x |
SpatRaster |
main |
character. Main plot titles (one for each layer to be plotted). You can use arguments |
loc.main |
numeric of character to set the location of the main title. Either two coordinates, or a character value such as "topleft") |
nc |
positive integer. Optional. The number of columns to divide the plotting device in (when plotting multiple layers) |
nr |
positive integer. Optional. The number of rows to divide the plotting device in (when plotting multiple layers) |
maxnl |
positive integer. Maximum number of layers to plot (for a multi-layer object) |
maxcell |
positive integer. Maximum number of cells to use for the plot |
box |
logical. Should a box be drawn around the map? |
plg |
see |
pax |
see |
range |
numeric. minimum and maximum values to be used for the continuous legend |
... |
arguments passed to |
plot
and see rasterVis::levelplot
and tidyterra::autoplot
for more sophisticated panel plots.