Is there an R equivalent of GRASS GIS's r.neighbors range?

297 views Asked by At

A couple of thousand DEM geotiffs are erroring out in QGIS GRASS r.neighbors function using these parameters

GRASS r.neighbors neighborhood operation=range, neighborhood size=3

with the following error :-

2021-04-23T15:51:51     WARNING    Duplicate parameter coordinates registered for alg v.net.visibility

QGIS GRASS r.neighbors issue

I wanted to replicate this operation in R.

Looks like the only built in focal() functions are mean(), var() not range()? And the exact extents of the output raster does not match the input raster extents unlike GRASS?

Is there a matrix expression equivalent of the GRASS r.neighbors neighborhood operation=range, neighborhood size=3 in the focal() function or in R in general?

R focal function reference

1

There are 1 answers

4
Robert Hijmans On

I assume that with "range" you refer to the difference between the focal min and max value? You can compute that in (at least) two ways

library(terra)
f <- system.file("ex/elev.tif", package="terra")
r <- rast(f)
 
xmn <- focal(r, 3, min)
xmx <- focal(r, 3, max)
rng <- xmx - xmn

or like this

x <- focal(r, 3, function(i) diff(range(i)))

The results are slightly different where there are NAs. You can use na.rm=TRUE.