首页 > 解决方案 > 如何在 R 中使用 ifelse(条件语句)覆盖两个栅格?

问题描述

我有两个栅格(图像),并希望使用以下代码覆盖它们:

# 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

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

谢谢。

标签: rif-statementoverlayraster

解决方案


您需要一个仅使用矢量化运算符的函数。在这种情况下,布尔算术应该既成功又更有效

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)

我认为我不需要使用Vectorizearound myFunenter code here但是当我将其留在调用中时,结果似乎更有可能是正确的overlay

> 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

当我取出 Vectorize 步骤时,我没有收到错误,但我得到了全零。


推荐阅读