I have two rasters that have the same extent and resolution. I want to overlay the second raster on the first and add the values, but only apply the overlay function to cells of the first raster that are 5.
library(terra)
r <- rast(nrow = 45, ncol = 90)
values(r) <- 1:ncell(r)
r2 <- rast(nrow = 45, ncol = 90)
values(r2) <- 1
Something like this.
terra::overlay(r, r2, fun = function(x,y){
x1 <- x[x==5]
return(x1 + y)
})
It is not clear in your question what values you want for the cells that are not 5 in the first raster (the first raster, second raster, NA?). Here I am assuming you want the values of the first raster.
With terra
you can use ifel
library(terra)
r1 <- rast(nrow = 10, ncol = 10, xmin=0, xmax=1, ymin=0, ymax=1)
r1 <- init(r1, 1:5)
r2 <- rast(nrow = 10, ncol = 10, xmin=0, xmax=1, ymin=0, ymax=1)
values(r2) <- 10
x <- ifel(r1 == 5, r1 + r2, r1)
plot(x)
or with lapp
(~overlay)
f <- function(x, y){
i <- x==5
x[i] <- x[i] + y[i]
return( x)
}
z <- lapp(c(r1, r2), f)
With raster::overlay
library(raster)
rr1 <- raster(nrow = 10, ncol = 10, xmn=0, xmx=1, ymn=0, ymx=1)
values(rr1) <- rep(1:5, 20)
rr2 <- raster(nrow = 10, ncol = 10, xmn=0, xmx=1, ymn=0, ymx=1)
values(rr2) <- 10
xx <- overlay(rr1, rr2, fun =f)