Your question is not very clear and you do not provide example data. My understanding is that you want to assign values to raster cells that are covered by a polygon, but only values that are currently NA
, and that they should be similar to the nearby raster cell values. Your image suggests that you rasterized a line and the whole thing might be easier if you backtracked a bit --- but you provide insufficient information to comment. If my understanding of your goal is right, you could do something like this:
Example data
library(raster)
r <- raster(resolution=5)
values(r) <- 1:ncell(r)
cds <- rbind(c(-160,-20), c(-140,55), c(10, 0), c(140,60))
line <- spLines(cds)
r <- mask(r, line)
poly <- buffer(line, 10)
Solution: assign similar values to neighboring cells. The size of the window depends on the polygon used, but 5x5 works for the example. Then use mask to remove cells that are outside the polygon
rr <- focal(r, matrix(1, 5, 5), fun=mean, na.only=TRUE, na.rm=TRUE)
x <- mask(rr, poly)
Instead of with raster
you can also do this with terra
(it is faster)
library(terra)
r <- rast(resolution=5)
values(r) <- 1:ncell(r)
cds <- rbind(c(-160,-20), c(-140,55), c(10, 0), c(140,60))
line <- vect(cds, "lines", crs=crs(r))
r <- mask(r, line)
poly <- buffer(line, 1000000)
rr <- focal(r, matrix(1, 5, 5), fun=mean, na.only=TRUE, na.rm=TRUE)
x <- mask(rr, poly)
st_buffer
to create a buffered version of the polygon and then rasterize that?