focal2 | R Documentation |
Applies a focal filter with weighted neighborhood w
on a raster. The weights (w
) can be added to, subtracted from, multiplied by or divided with the raster values (as specified with weight_fun
). The focal cell is then taken as the mean, sum, minimum or maximum of the weighted values (as specified with fun
). Input and output are rasters of class stars
, single-band (i.e., only '"x"' and '"y"' dimensions), with one attribute.
focal2(
x,
w,
fun = "mean",
weight_fun = "*",
na.rm = FALSE,
mask = FALSE,
na_flag = -9999
)
x |
A raster (class |
w |
Weights matrix defining the neighborhood size around the focal cell, as well as the weights. For example, |
fun |
A function to aggregate the resulting values for each neighborhood. Possible values are: |
weight_fun |
An operator which is applied on each pair of values comprising the cell value and the respective weight value, as in |
na.rm |
Should |
mask |
If |
na_flag |
Value used to mark |
The filtered stars
raster.
The raster is "padded" with (nrow(w)-1)/2
more rows and columns of NA
values on all sides, so that the neighborhood of the outermost rows and columns is still a complete neighborhood. Those rows and columns are removed from the final result before returning it. This means, for instance, that the outermost rows and columns in the result will be NA
when using na.rm=FALSE
.
The function interface was inspired by function raster::focal
. The C code for this function is a modified and expanded version of the C function named applyKernel
included with R package spatialfil
.
# Small example
data(dem)
dem_mean3 = focal2(dem, matrix(1, 3, 3), "mean")
r = c(dem, round(dem_mean3, 1), along = 3)
r = st_set_dimensions(r, 3, values = c("input", "output (mean, k=3)"))
plot(r, text_values = TRUE, breaks = "equal", col = terrain.colors(11))
# Larger example
data(carmel)
carmel_mean15 = focal2(carmel, matrix(1, 15, 15), "mean")
r = c(carmel, carmel_mean15, along = 3)
r = st_set_dimensions(r, 3, values = c("input", "output (mean, k=15)"))
plot(r, breaks = "equal", col = terrain.colors(11))
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.