Raster algebra
Many generic functions that allow for simple and elegant raster algebra
have been implemented for SpatRaster
objects, including the normal
algebraic operators such as +
, -
, *
, /
, logical
operators such as >
, >=
, <
, ==
, !
} and functions
such as abs
, round
, ceiling
, floor
, trunc
, sqrt
,
log
, log10
, exp
, cos
, sin
, max
, min
,
range
, prod
, sum
, any
, all
. In these functions you
can mix terra
objects with numbers, as long as the first argument is
a terra
object.
library(terra)
## terra 1.8.6
# create an empty SpatRaster
r <- rast(ncol=10, nrow=10)
# assign values to cells
values(r) <- 1:ncell(r)
s <- r + 10
s <- sqrt(s)
s <- s * r + 5
values(r) <- runif(ncell(r))
r <- round(r)
r <- r == 1
You can also use replacement functions (not yet supported)
s[r] <- -0.5
s[!r] <- 5
s[s == 5] <- 15
If you use multiple SpatRaster
objects (in functions where this is
relevant, such as range), these must have the same resolution and
origin. The origin of a SpatRaster
object is the point closest to
(0, 0) that you could get if you moved from a corners of a
SpatRaster
object towards that point in steps of the x
and
``y
resolution. Normally these objects would also have the same
extent, but if they do not, the returned object covers the spatial
intersection of the objects used.
When you use multiple multi-layer objects with different numbers or layers, the ‘shorter’ objects are ‘recycled’. For example, if you multiply a 4-layer object (a1, a2, a3, a4) with a 2-layer object (b1, b2), the result is a four-layer object (a1b1, a2b2, a3b1, a3b2).
r <- rast(ncol=5, nrow=5)
values(r) <- 1
s <- c(r, r+1)
q <- c(r, r+2, r+4, r+6)
x <- r + s + q
x
## class : SpatRaster
## dimensions : 5, 5, 4 (nrow, ncol, nlyr)
## resolution : 72, 36 (x, y)
## extent : -180, 180, -90, 90 (xmin, xmax, ymin, ymax)
## coord. ref. : lon/lat WGS 84 (CRS84) (OGC:CRS84)
## source(s) : memory
## names : lyr1, lyr2, lyr3, lyr4
## min values : 3, 6, 7, 10
## max values : 3, 6, 7, 10
Summary functions (min, max, mean, prod, sum, Median, cv, range, any,
all) always return a SpatRaster
object. Perhaps this is not
obvious when using functions like min, sum or mean.
a <- mean(r, s, 10)
b <- sum(r, s)
st <- c(r, s, a, b)
sst <- sum(st)
sst
## class : SpatRaster
## dimensions : 5, 5, 1 (nrow, ncol, nlyr)
## resolution : 72, 36 (x, y)
## extent : -180, 180, -90, 90 (xmin, xmax, ymin, ymax)
## coord. ref. : lon/lat WGS 84 (CRS84) (OGC:CRS84)
## source(s) : memory
## name : sum
## min value : 17.33333
## max value : 17.33333
Use global
if instead of a SpatRaster
you want a single number
summarizing the cell values of each layer.
global(st, 'sum')
## sum
## lyr.1 25.0000
## lyr.1.1 25.0000
## lyr.1.2 50.0000
## lyr1 100.0000
## lyr2 108.3333
## lyr1.1 50.0000
## lyr2.1 75.0000
global(sst, 'sum')
## sum
## sum 433.3333