patch105
patch105

Reputation: 39

Raster overlay applied to subset of first raster

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)

Raster 1

r2 <- rast(nrow = 45, ncol = 90)
values(r2) <- 1

Raster 2

Something like this.

terra::overlay(r, r2, fun =  function(x,y){
  x1 <- x[x==5]
  return(x1 + y)
  })

Upvotes: 1

Views: 565

Answers (2)

Robert Hijmans
Robert Hijmans

Reputation: 47156

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)

Upvotes: 2

Elia
Elia

Reputation: 2584

with you example somthing like this work properly:

library(raster)
mysum <- function(r,r2,value){
v<- r2[r==value]+value
r[r==value] <- v
return(r)
}
y <- mysum(r,r2,5)

probably there are more efficient methods for bigger raster, but this is simple and don't require overlay

Upvotes: 1

Related Questions