Skip to main content
added 38 characters in body
Source Link

Spacedman's solution is so nice that you may want to see it twice (but now with terra)

library(terra)
rr <- rast(resolution=5)
values(rr) <- 1:ncell(rr)
cds <- rbind(c(-160,-20), c(-140,55), c(10, 0), c(140,60))
lin <- vect(cds, "lines")
rr <- mask(rr, lin)

rp <- as.points(rr)

bf <- buffer(rr, width=1600000)
bf <- ifel(bf, 1, NA)
bf <- mask(bf, rr, inverse=TRUE)
bp <- as.points(bf)

# nearest points (cells) on line and values
n <- nearest(bp, rp)
v <- extract(rr, rp)

# assign back to the raster
cell <- cellFromXY(rr, cbind(n$from_x, n$from_y))
rr[cell] <- v[n$to_id,2]
plot(rr)

Spacedman's solution is so nice that you may want to see it twice (but now with terra)

library(terra)
rr <- rast(resolution=5)
values(rr) <- 1:ncell(rr)
cds <- rbind(c(-160,-20), c(-140,55), c(10, 0), c(140,60))
lin <- vect(cds, "lines")
rr <- mask(rr, lin)

rp <- as.points(rr)

bf <- buffer(rr, width=1600000)
bf <- ifel(bf, 1, NA)
bp <- as.points(bf)

# nearest points (cells) on line and values
n <- nearest(bp, rp)
v <- extract(rr, rp)

# assign back to the raster
cell <- cellFromXY(rr, cbind(n$from_x, n$from_y))
rr[cell] <- v[n$to_id,2]
plot(rr)

Spacedman's solution is so nice that you may want to see it twice (but now with terra)

library(terra)
rr <- rast(resolution=5)
values(rr) <- 1:ncell(rr)
cds <- rbind(c(-160,-20), c(-140,55), c(10, 0), c(140,60))
lin <- vect(cds, "lines")
rr <- mask(rr, lin)

rp <- as.points(rr)

bf <- buffer(rr, width=1600000)
bf <- ifel(bf, 1, NA)
bf <- mask(bf, rr, inverse=TRUE)
bp <- as.points(bf)

# nearest points (cells) on line and values
n <- nearest(bp, rp)
v <- extract(rr, rp)

# assign back to the raster
cell <- cellFromXY(rr, cbind(n$from_x, n$from_y))
rr[cell] <- v[n$to_id,2]
plot(rr)
Source Link

Spacedman's solution is so nice that you may want to see it twice (but now with terra)

library(terra)
rr <- rast(resolution=5)
values(rr) <- 1:ncell(rr)
cds <- rbind(c(-160,-20), c(-140,55), c(10, 0), c(140,60))
lin <- vect(cds, "lines")
rr <- mask(rr, lin)

rp <- as.points(rr)

bf <- buffer(rr, width=1600000)
bf <- ifel(bf, 1, NA)
bp <- as.points(bf)

# nearest points (cells) on line and values
n <- nearest(bp, rp)
v <- extract(rr, rp)

# assign back to the raster
cell <- cellFromXY(rr, cbind(n$from_x, n$from_y))
rr[cell] <- v[n$to_id,2]
plot(rr)