overlay rasters at a given value

浪尽此生 提交于 2021-02-08 06:15:10

问题


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)

回答1:


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).



来源:https://stackoverflow.com/questions/45009090/overlay-rasters-at-a-given-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!