DFinch
DFinch

Reputation: 139

overlay rasters at a given value

I am relatively new to using R and working with GIS data.

I am trying to create a function to overlay two Raster layers, only when one of the rasters (in this case raster1) is at a certain value (in this case 0). I have tried numerous options in doing this but they don't seem to work. My last attempt is provided below, and it runs but the output just says NULL and it does not plot.

library(raster)

raster1 <- raster(ncols=10,nrows=10) 
raster2 <- raster(ncols=10,nrows=10) 

values(raster1) <- round(runif(ncell(raster1)))
values(raster2) <- round(runif(ncell(raster2)))

plot(raster1)
plot(raster2)

overlay_zero <- function (x, y) {
if (isTRUE(x == 0)) {
  overlay(x, y, fun=function(x,y) {return(x+y)})}
} 


z <- overlay_zero(raster1, raster2)
z
plot(z)

Upvotes: 2

Views: 900

Answers (1)

maRtin
maRtin

Reputation: 6516

overlay_ras <- function(ras1,ras2,value=0){

  result              <- ras1
  result[ras1==value] <- ras1[ras1==value] + ras2[ras1==value]
  return(result)

}

overlaid <- overlay_ras(raster1,raster2,0)

This will do the trick. The function takes two rasters and a value which will be used to determine the cells affected by the overlay (addition).

Upvotes: 1

Related Questions