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 SpatRaster
focalCor(x, w=3, fun, ..., fillvalue=NA,
filename="", overwrite=FALSE, wopt=list())
SpatRaster
SpatRaster with at least two layers
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 focal
A function with at least two arguments (one for each layer)
additional arguments for fun
numeric. The value of the cells in the virtual rows and columns outside of the raster
character. Output filename
logical. If TRUE
, filename
is overwritten
additional arguments for writing files as in writeRaster
layerCor
, focalReg
, focal
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)
# suppress warning "the standard deviation is zero"
suppressWarnings(x <- focalCor(r, w=5, cor))
# this warning does not occur when using a larger window
x <- focalCor(r, w=9, function(x, y) cor(x, y))
plot(x)
Run the code above in your browser using DataLab