Fill in gaps (e.g. not single cells) of NA values in raster using a neighborhood analysis

Viewed 2815

With the raster below, with an increased number of NA values

library(raster)
filename <- system.file("external/test.grd", package="raster")
r <- raster(filename)
r[r<300] <- NA
summary(getValues(r))

is it possible to 'fill in' only the NA cells? I have been using this helpful post but as seen below, NA values remain in the final product.

fill.na <- function(x, i=5) {
  if( is.na(x)[i] ) {
    return( round(mean(x, na.rm=TRUE),0) )
  } else {
    return( round(x[i],0) )
  }
}  

r2 <- focal(r, w = matrix(1,3,3), fun = fill.na, 
            pad = TRUE, na.rm = FALSE )
summary(getValues(r2))

I suspect the issue is the contiguous areas with NA values and am wondering if there are other options for 'filling in' gaps of missing data.

1 Answers
Related