focal,GRaster-method | R Documentation |
This function calculates statistics on a moving "neighborhood" of cells of a raster. The neighborhood can be a square, circle, or a user-defined set of cells (with or without weights).
## S4 method for signature 'GRaster'
focal(x, w = 3, fun = "sum", circle = FALSE, quantile = 0.5)
x |
A |
w |
Numeric integer or a square matrix with an odd number of rows and columns: The size and nature of the neighborhood:
|
fun |
Character: Name of the function to apply to the neighborhood:
The center cell value is always included in the calculations, and all calculations ignore |
circle |
Logical: If |
quantile |
Numeric between 0 and 1, inclusive: Quantile to calculate when |
A GRaster
.
terra::focal()
, GRASS manual page for module r.neighbors
(see grassHelp("r.neighbors")
)
if (grassStarted()) {
# Setup
library(terra)
# Example data
madElev <- fastData("madElev")
# Convert a SpatRaster to a GRaster:
elev <- fast(madElev)
# Focal calculations:
sums <- focal(elev, fun = "sum")
means <- focal(elev, fun = "mean")
# Focal calculations on a circular window:
sds <- focal(elev, fun = "sd") # square
sdsCircle <- focal(elev, fun = "sd", circle = TRUE) # circle
sds
sdsCircle
plot(sds - sdsCircle)
# Focal calculations with user-defined weights:
w <- matrix(c(1, 0, 1, 0, 1, 0, 1, 0, 1), ncol = 3)
w
sumsWeighted <- focal(elev, fun = "sum", w = w)
s <- c(sums, sumsWeighted)
minmax(s)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.