rspatial/terra

Global Moran's I in autocor function does not correctly count neighbours

Closed this issue · 1 comments

This line in the global Moran's I calculation (autocor.R line 156) will return NA for any cell with an adjacent NA cell, and thus does not correctly count neighbours for any cell with an adjacent NA.

W <- focal( zz, w=w, fun="sum")

In extreme cases this leads to a failure to calculate Global Moran's I (autocorr returns NA).
In less extreme cases this leads to slightly inflated values of I being returned.

Here's some code to replicate this issue in an extreme case:

exampleRast_base <- ifel((0==rast(diag(1,5,5))),NA,1) # Generate a diagonal raster -> an extreme case
exampleRast      <- mask(focal(exampleRast_base,3,'sum',na.rm = TRUE),exampleRast_base) # Adjust the raster to add some variance
x <- exampleRast
w <- matrix(c(1,1,1,1,0,1,1,1,1),3)
autocor(x, w, method="moran", global=TRUE) # -> Returns NA

And here's some code that I think will properly count neighbours if we replace line 156 with it. Notably, we need to apply a mask using the original raster after adding na.rm = TRUE, otherwise the autocorr function will produce slightly deflated values for I.

W <- mask(focal( zz, w=w, fun="sum", na.rm = TRUE),x)

I'm unsure whether a similar issue exists for the local or Geary calculations - I'm not particularly familiar with how they are calculated.

OS is Windows 10

> packageVersion("terra")
[1] ‘1.7.55’
> terra::gdal(lib="all")
   gdal    proj    geos 
"3.5.2" "8.2.1" "3.9.3" 

Thank you very much and sorry for the long response time. Fixed as suggested.