I think this does most of what you want, except perhaps the averaging bit. It uses the fact that the nearest point on the raster line to any other grid point will be the orthogonal distance to the line.
First get all the non-NA locations as an x,y,value matrix:
rp = rasterToPoints(r)
Then construct the buffer area. The r
raster is lat-long so you need to buffer it in a huge number of metres to get something usable. Your coordinate system may vary (and I couldn't find a way to make raster::buffer
use degrees. Anyway...)
buf = raster::buffer(r, width=1600000)
plot(buf)
Then get the x,y,value of all the non-zero buffer points. The values will all be 1
bp = rasterToPoints(buf)
Now use the FNN
package (installable from CRAN) to get the nearest (k=1) neighbour of each buffer point to the points on the line:
library(FNN)
nn = knnx.index(data=rp[,1:2], query=bp[,1:2],k=1)
That gives us a matrix with one column, which has the index of the point in rp
that is nearest to each point in bp
.
Make a copy of the buffer raster for output. You can use buf
if you don't need it anymore:
nr = buf
Now replace the 1 values in nr
with values in the source raster points by looking up the value in the source raster points (column 3) in the matching rows:
values(nr)[!is.na(nr[])] = rp[nn[,1],3]
plot(nr)
Which I think is, apart from this "averaging" bit, what you are after. I'd test it with a few more lines (particularly try a vertical and horizontal one) to see what you get.