Search code examples
rbufferraster

Assigning cell values of one raster to the adjacent cells of another using R


I have two spatially projected raster objects that are NOT overlapping. One raster (rk) has reliable values and the values of the other one (dnn) is unreliable.

#reliable
plot(rk)
#unreliable
plot(dnn, add=TRUE, col='gray80')

In this figure (showing a subset of my data), the colors are representing the values of the reliable raster whereas I plotted all unreliable raster pixels as gray. I want to change the unreliable values based on the reliable values. An easier solution to the problem might be assigning the mean of the nearest neighbor values of the surrounding reliable pixels (mean) to the unreliable ones and thereafter merging those together.

I thought the first step might be finding a buffer around each of the gray cells, then finding the mean values within each buffer. However, to deal with the NAs (not including those in computation), I determined the non-NA indexes first

library(raster)
#selecting those index that are non-NAs
idx<-is.na(getValues(dnn))
idx<-which(idx==FALSE)
> length(idx)
[1] 602
#proving that the determined idx is correct
> sum(!is.na(getValues(dnn)))
[1] 602

But I'm getting an error while doing the buffering

#doing buffer for those idx only
for (i in idx[i]) {b(i)<-buffer(dnn[i], width=500)}
Error in (function (classes, fdef, mtable)  : 
  unable to find an inherited method for function ‘buffer’ for signature ‘"numeric"’

I'm not sure if this is the right way, even after getting the buffers, calculating the mean (I expect to use the zonal statistics) and assigning those to corresponding gray cells doesn't look like an easy task to me. Any suggestions??


Solution

  • Use a point-pattern approach. Treat each unreliable cell as an x,y coordinate, and all the reliable cells as x,y,Z values. Put the x,y,Z into a spatial interpolation algorithm, such as simple inverse distance weighting or less-simple Kriging, and then predict at the unreliable x,y locations. Put the predicted values back in the grid at the right place.

    The automap package can help you here (also gstat and the R Spatial Task View).