1

I have a big raster with some NA cells that need to be filled. I want to fill it by Inverse Distance Weighting (IDW), by considering the 9 nearest [valid] cells. I used the idw function from the gstat package, but although it works, it takes ages to complete the task (my original raster comprises 6232186 cells that I include in the gstat call, and I have ~14000 gaps to be filled). As I have to repeat this task with several rasters, I'm looking for a faster solution. Does anyone have a suggestion?

I was thinking about using the focal from the raster or terra packages, but to be sincere I didn't understood very well how to set a matrix of weights to get a result like the IDW... Also, I would like to get the nearest valid cells (thus, suppose that in a square focal does not find valid cells, it would look further away to find more valid cells).

Just to give an example, suppose that in the following raster I need to fill the cells of number 310 and 330:

r <- raster(nrow = 20, ncol = 20)
r[1:300] <- sample(1:4, size = 300, replace = T)
plot(r)

gaps <- xyFromCell(r, c(310, 330))
points(gaps)

Raster to be filled

By using focal with a 3x3 square I would get the mean for just the cell 310 (and without the inverse weighting and also without getting 9 valid cells):

filed <- raster::focal(r, matrix(1, nrow = 3, ncol = 3), fun = mean, NAonly = T, na.rm = T)
plot(filed);points(gaps)

Filled raster

I appreciate any help/suggestion!

  • 1
    Another approach using [terra](https://stackoverflow.com/questions/71801889/how-to-fill-in-missing-na-values-in-raster-with-terra-package), note the `w=9`... and check which `packageVersion('terra') you're using. – Chris Aug 07 '22 at 21:47
  • Thanks for the suggestion! However, this solution produces the same result as the one with raster. Because it don't look for the 9 nearest cells (and just for a square of 9 cells around the NA point) it will just fill the point that is close to the valid cells. My question is exactly if there is any way to get a result similar to `gstat::idw` using focal. – silasprincipe Aug 09 '22 at 12:18

1 Answers1

2

One approach would be to use a while loop to increase the window/matrix of the focal function until all NA cells are filled.

With terra it would be like this:

library(terra)

r <- rast(nrow = 20, ncol = 20)
r[1:300] <- sample(1:4, size = 300, replace = T)

gaps <- xyFromCell(r, c(310, 330))

w <- 1
filled <- r # just in case you want to keep the original

to_fill <- any(is.na(values(filled)))

# for big rasters you could use (same inside loop)
# to_fill <- global(filled, function(x) any(is.na(x)))[,1]

while(to_fill) {
 w <- w + 2  
 filled <- focal(filled, w = w, fun = mean, na.policy = "only", na.rm = T) 
 to_fill <- any(is.na(values(filled)))
}

plot(filled)
points(gaps)

enter image description here

Fernando.-
  • 133
  • 1
  • 7