Monday, 4 January 2016

raster - Fill the gaps using nearest neighbors


I want to fill the NA values using the average values of the nearest neighbors:


r <- raster(matrix(1:16, nrow=8, ncol=8))

r[r==12] <- NA

Answer



You can fill in the NA values using the focal function with the na.rm argument set to FALSE and pad to TRUE.


library(raster)
r <- raster(matrix(1:16, nrow=8, ncol=8))
r[r==12] <- NA

Function to replace the focal value with the mean of a 3x3 window if NA. If the window size increases the index value [i] needs to change as well (eg., for a 5x5 window the index would be 13).


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) )
}
}

Pass the fill.na function to raster::focal and check results. The pad argument creates virtual rows/columns of NA values to keep the vector length constant along the edges of the raster. This is why we can always expect the fifth value of the vector to be the focal value in a 3x3 window thus, the index i=5 in the fill.na function.


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


as.matrix(r)
as.matrix(r2)

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...