如何在 R 中使用 ifelse(条件语句)叠加两个栅格?

How to overlay two Rasters using ifelse (Conditional Statements) in R?

我有两个光栅(图像),并希望使用此代码叠加它们:

# Getting the images
library(raster)

URL1 <- "https://www.dropbox.com/s/6jjz7ou1skz88wr/raster_1.tif?dl=1"
URL2 <- "https://www.dropbox.com/s/d5xuixohjqfnfze/raster_2.tif?dl=1"

download.file(URL1, destfile=paste0(getwd(),"/", "raster_1.tif"), method="auto", mode="wb", timeout="6000")
download.file(URL2, destfile=paste0(getwd(),"/", "raster_2.tif"), method="auto", mode="wb", timeout="6000")

# Reading the images 
raster_1 <- raster(list.files(pattern="raster_1.tif$"))
raster_2 <- raster(list.files(pattern="raster_2.tif$"))

# Overlaying
myFun <- function(x,y){ifelse(x==0 && y==0, 0, ifelse(x==1 && y==0, 2, ifelse(x==1 && y>0, y)))}

( res <- overlay(stack(raster_1 ,raster_2), fun = Vectorize(myFun) ) )

### R gives this error
Error in .overlayList(x, fun = fun, filename = filename, forcefun = forcefun,  : 
  cannot use this formula, probably because it is not vectorized

如果有人能帮助我,我将不胜感激。

谢谢。

您需要一个仅使用向量化运算符的函数。这是布尔运算应该既成功又更有效的情况

myFun <- function(x,y){ 0*(x==0 && y==0)+ 
                        2*(x==1 && y==0)+
                        y*(x==1 && y>0) }

有些边缘情况似乎没有涵盖。 x 可以是 0 或 1 以外的值吗? y 可以是负数吗?

在 运行 我的版本之后我得到:

> ( res <- overlay(stack(raster_1 ,raster_2), fun = Vectorize(myFun) ) )
class       : RasterLayer 
dimensions  : 2958, 1642, 4857036  (nrow, ncol, ncell)
resolution  : 500, 500  (x, y)
extent      : -171063.8, 649936.2, 5317253, 6796253  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=utm +zone=12 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs 
data source : in memory
names       : layer 
values      : 0, 14751  (min, max)

我认为我不需要在 myFunenter code here 周围使用 Vectorize,但是当我将它留在对 [ 的调用中时,结果似乎更有可能是正确的=18=]:

> Hmisc::describe(values(res))
values(res) 
       n  missing distinct     Info     Mean      Gmd      .05      .10      .25 
 3222508  1634528     1502    0.727     4918     6403        0        0        0 
     .50      .75      .90      .95 
       0    13898    14082    14168 

Value            0   13000   13200   13400   13600   13800   14000   14200   14400
Frequency  2089448      67     578   10515   69031  249817  523241  226628   46191
Proportion   0.648   0.000   0.000   0.003   0.021   0.078   0.162   0.070   0.014

Value        14600   14800
Frequency     6876     116
Proportion   0.002   0.000

当我取出矢量化步骤时,我没有收到错误,而是全部为零。

不清楚您真正想要实现的目标,可能有更好的解决方案。在您的示例数据中,Y (raster_2) 没有零值。这表明您想要 raster_2 的值,其中 raster_1 不是 0?可以这样实现:

m <- mask(raster_2, raster_1, maskvalue=0)

我认为 42- 的 myFun 有一个问题,它 returns 0 当 none 的条件为真时,特别是当 (x == 0 & y > 0)

要使其与 overlay 一起使用,请将 && 替换为 &

myFunV <- function(x,y){ 
                    0*(x==0 & y==0)+ 
                    2*(x==1 & y==0)+
                    y*(x==1 & y>0) }                        

res <- overlay(raster_1, raster_2, fun = myFunV)

(但是,我再次怀疑这是否适合您的需求)