Learn R Programming

terra (version 0.5-2)

focal: Focal values

Description

Calculate focal ("moving window") values for the neighborhood of focal cells using a matrix of weights, perhaps in combination with a function.

Usage

# S4 method for SpatRaster
focal(x, w=3, na.rm=TRUE, fillvalue=NA, fun="sum", 
            filename="", overwrite=FALSE, wopt=list(), ...)

Arguments

x

SpatRaster

w

matrix of weights (the moving window), e.g. a 3 by 3 matrix with values 1; see Details. The matrix does not need to be square, but the sides must be odd numbers. If you need even sides, you can add a column or row with weights of zero

na.rm

logical. If TRUE, NA will be removed from focal computations. The result will only be NA if all focal cells are NA. Except for some special cases (weights of 1, functions like min, max, mean), using na.rm=TRUE is generally not a good idea in this function because it will unbalance the effect of the weights

fillvalue

numeric. The value of the cells of the padded rows and columns

fun

function (optional). The function fun should take multiple numbers, and return a single number. For example mean, modal, min or max. It should also accept a na.rm argument (or ignore it, e.g. as one of the 'dots' arguments. For example, length will fail, but function(x, ...){na.omit(length(x))} works.

filename

character. Output filename. Optional

overwrite

logical. If TRUE, filename is overwritten

wopt

list. Options for writing files as in writeRaster

...

additional arguments. None implemented

Value

SpatRaster

Details

focal uses a matrix of weights for the neighborhood of the focal cells. The default function is sum. It is computationally much more efficient to adjust the weights-matrix than to use another function through the fun argument. Thus while the following two statements are equivalent (if there are no NA values), the first one is faster than the second one:

a <- focal(x, w=matrix(1/9, nc=3, nr=3))

b <- focal(x, w=matrix(1,3,3), fun=mean)

There is, however, a difference if NA values are considered. One can use the na.rm=TRUE option which may make sense when using a function like mean. However, the results would be wrong when using a weights matrix.

Laplacian filter: filter=matrix(c(0,1,0,1,-4,1,0,1,0), nrow=3)

Sobel filter: filter=matrix(c(1,2,1,0,0,0,-1,-2,-1) / 4, nrow=3)

Examples

Run this code
# NOT RUN {
r <- rast(ncols=36, nrows=18, xmn=0)
values(r) <- 1:ncell(r)

x <- focal(r, w=3, fun=mean) 
# }

Run the code above in your browser using DataLab