
Cell level regression
regress.RdRun a regression model for each cell of a SpatRaster. The independent variable can be defined either by:
a
numericvector of lengthnlyr(y)– one covariate that varies across the layers but is constant across cells (e.g. time);a
SpatRasterof the same number of layers asy– one covariate that varies both across layers and across cells;a
data.framewith one row per layer ofyand one column per predictor – multiple covariates that vary across layers but are constant across cells (e.g. an experimental design like NPK fertilizer levels).
Usage
# S4 method for class 'SpatRaster,numeric'
regress(y, x, formula=y~x, na.rm=FALSE, cores=1, filename="", overwrite=FALSE, ...)
# S4 method for class 'SpatRaster,SpatRaster'
regress(y, x, formula=y~x, na.rm=FALSE, cores=1, filename="", overwrite=FALSE, ...)
# S4 method for class 'SpatRaster,data.frame'
regress(y, x, formula=NULL, na.rm=FALSE, cores=1, filename="", overwrite=FALSE, ...)Arguments
- y
SpatRaster. The dependent variable. Each layer is one observation per cell.
- x
The independent variable(s):
SpatRasterof the same number of layers asy;numericvector of lengthnlyr(y);data.framewithnlyr(y)rows and one column per predictor (noNAs allowed).
- formula
regression formula. For the
numericandSpatRastermethods the default isy ~ x; you can add additional terms such asI(x^2). For thedata.framemethod the default (whenformula=NULL) isy ~ ., expanding to all columns ofx; you can also pass a custom formula whose right-hand side references the column names ofx(the left-hand side is ignored).- na.rm
logical. If
TRUE, layers withNAresponse in a given cell are dropped before fitting. A cell whose remaining row count drops below the number of regression coefficients yields allNAs.- cores
positive integer. If
cores > 1, a 'parallel' package cluster with that many cores is created and used. You can also supply a cluster object.- filename
character. Output filename
- overwrite
logical. If
TRUE,filenameis overwritten- ...
list with named options for writing files as in
writeRaster
Value
SpatRaster. One layer per regression coefficient, named after the corresponding column of model.matrix(formula, x) (e.g. (Intercept), the names of the predictors, and any interaction or polynomial terms).
Examples
s <- rast(system.file("ex/logo.tif", package="terra"))
x <- regress(s, 1:nlyr(s))
# data.frame method: a small NPK fertilizer experiment.
# Suppose `y` has one layer per (N, P, K) treatment.
if (FALSE) { # \dontrun{
NPK <- data.frame(
N = c(0, 50, 100, 0, 50, 100, 0, 50, 100),
P = c(0, 0, 0, 25, 25, 25, 50, 50, 50),
K = c(0, 10, 20, 0, 10, 20, 0, 10, 20)
)
# Default formula y ~ N + P + K:
fit <- regress(y, NPK)
# Custom formula with interactions and a quadratic term:
fit2 <- regress(y, NPK, formula = yield ~ N + P + K + I(N^2) + N:P)
} # }