Become an expert in R — Interactive courses, Cheat Sheets, certificates and more!
Get Started for Free

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 signature 'SpatRaster'
focal(x, w=3, fun="sum", na.rm=TRUE, na.only=FALSE, 
			fillvalue=NA, expand=FALSE, filename="", ...)

Arguments

x

SpatRaster

w

window. The window can be defined as one (for a square) or two numbers (row, col); or with an odd-sized weights matrix. See Details.

fun

function that takes multiple numbers, and returns a single number. For example mean, modal, min or max. It should also accept a na.rm argument, either as actual argument or through use of ...

na.rm

logical. Should missing values be removed?

na.only

logical. Should only missing values in x be changed?

fillvalue

numeric. The value of the cells in the virtual rows and columns outside of the raster

expand

logical. If TRUE The value of the cells in the virtual rows and columns outside of the raster are set to be the same as the value on the border

filename

character. Output filename

...

additional arguments for writing files as in writeRaster

Details

focal

The window used must have odd dimensions. If you need even sides, you can use a matrix and add a column or row with weights of zero.

Window values are typically 0 or 1, or a value between 0 and 1 if you are using a rectangular area and/or the "sum" function. They can also be NA; these are ignored in the computation. That can be useful to compute the mean, min, or max value for a non-rectangular area.

Example weight matrices

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)

Value

SpatRaster

Examples

r <- rast(ncols=10, nrows=10, ext(0, 10, 0, 10))
values(r) <- 1:ncell(r)

#f <- focal(r, w=3, fun=function(x, ...) quantile(x, .25, ...), na.rm=TRUE) 

f <- focal(r, w=3, fun="mean") 

# the following two statements are equivalent:
a <- focal(r, w=matrix(1/9, nc=3, nr=3))
b <- focal(r, w=3, fun=mean, na.rm=FALSE)

# but this is different
d <- focal(r, w=3, fun=mean, na.rm=TRUE)

terra

Spatial Data Analysis

v1.2-10
GPL (>= 3)
Authors
Robert J. Hijmans [cre, aut] (<https://orcid.org/0000-0001-5872-2872>), Roger Bivand [ctb] (<https://orcid.org/0000-0003-2392-6140>), Karl Forner [ctb], Jeroen Ooms [ctb] (<https://orcid.org/0000-0002-4035-0289>), Edzer Pebesma [ctb] (<https://orcid.org/0000-0001-8049-7069>)
Initial release
2021-05-12

We don't support your browser anymore

Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.