0

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

Rose
  • 205
  • 3
  • 12

1 Answers1

1

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.

Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63
  • Thank you for the heads up. I've tried both these methods as is and have this error :- Error in .local(x, ...) : is.matrix(w) is not TRUE Did a workaround :- r_focal = focal(output_file, w = matrix(1, nrow = 3, ncol = 3), function(i) diff(range(i))) Just double checking this will give you the same output that you wanted? (i have an additional question I'll post up on stackoverflow, there are pixel wide gaps between tiled rasters, looks like the origin of the file has been shifted a pixel, outputfiles not adjacent to each other like the inputfiles, tried pad=TRUE + padValue=NA with no luck – Rose Apr 26 '21 at 23:17
  • 1
    You probably refer to focal with a RasterLayer, not with a SpatRaster (the terra focal method). There is no shifting. What you see is probably rows becoming NA. Otherwise `show(x)` your input and output data. – Robert Hijmans Apr 26 '21 at 23:23
  • It still happens using terra methods - ras(), and writeRaster() (outermost pixels are assigned NA) any other thoughts how to fix this? Thank you again – Rose Apr 27 '21 at 01:15
  • You can use na.rm=T, or use another fill value. Otherwise, please provide a simple example. – Robert Hijmans Apr 27 '21 at 04:35