0

I have a raster image for which I would like to interpolate the values for NA only. The missing NA's are usually in the border of the image. I am fairly new to R so I am not sure how exactly to do it. The accuracy of the values doesn't have to be higher and I would like to do just nearest neighbour interpolation. Any helps and suggestions or welcome. I have added a simplified code to genetae a raster which has NA values on the border but ideally this NA value would be on all 4 sides of the raster. I found a post similar to filling NA gaps Fill in gaps (e.g. not single cells) of NA values in raster using a neighborhood analysis but it doesnt work for me.

rast <- raster(nrow=10, ncol=10, crs='+proj=utm +zone=1 +datum=WGS84', xmn=0, xmx=1, ymn=0, ymx=1)
values(rast) <- 1:ncell(rast)
values(rast)[1:20] <- NA
noobie420
  • 3
  • 3

1 Answers1

3

I think you can use the focal function for that. If you have NAs at the border and other places, I think the below is the simplest approach

I use a bit more complex example data. The first two rows are NA, and there are also NAs in the middle

library(raster)

r <- raster(nrow=10, ncol=10, crs='+proj=utm +zone=1 +datum=WGS84', xmn=0, xmx=1, ymn=0, ymx=1)
values(r) <- 1:ncell(r)
r[c(1:2, nrow(r)), ] <- NA
r[, 1] <- NA
r[3:5, 3:5] <- NA
plot(r)

w <- matrix(1, 3, 3)  #c(0,1,0,1,0,1,0,1,0), nrow=3)
x <- focal(r, w, mean, na.rm=TRUE, NAonly=TRUE, pad=TRUE)
plot(x)

Because the first row did not have any neighbors that are not NA we need to run the last line again

xx <- focal(x, w, mean, na.rm=TRUE, NAonly=TRUE, pad=TRUE)

plot(xx)
text(r, cex=.8)
text(mask(xx, r, inverse=TRUE), col="red", cex=.8)

enter image description here

Note that on a raster with square cells, there are four (rook case) nearest neighbors and 4 others that are nearby on the diagonal. For the border row you could use this value for w to get the rook is not defined

w <- matrix(c(0,1,0,1,0,1,0,1,0), nrow=3)

#     [,1] [,2] [,3]
#[1,]    0    1    0
#[2,]    1    0    1
#[3,]    0    1    0

But that would not work for the other cells (nor for the 4 corner cells).

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63
  • Thanks for your reply. And this works for me. By did not work for me, I meant it was smoothening my entire raster. And I was not sure what was the cause for that. But this is exactly what I was looking for. – noobie420 Mar 05 '21 at 08:23