【发布时间】:2016-07-05 22:28:25
【问题描述】:
我在运行代码时发现在光栅包中的 overlay 内使用 ifelse 函数时出现了奇怪的行为。简而言之,如果每个栅格的前5个值是NA,函数就会报错。
为什么会这样?
下面是一个简短的代码,它模仿了我使用 R 3.2.3 和光栅版本 2.5-2 发现的问题,以及我正在考虑同时使用的一些临时解决方案。
谢谢
卡洛斯·阿尔贝罗
library(raster)
cob1d <- raster(matrix(1,nr=6,nc=6))
cob1 <- cob1d; cob2 <- cob1d; cob3 <- cob1d
overlay(cob1, cob2, cob3, fun=function(x1, x2, x3) ifelse(x1 > 0, x1 + x2 + x3, x3))
# class : RasterLayer
# dimensions : 6, 6, 36 (nrow, ncol, ncell)
# resolution : 0.1666667, 0.1666667 (x, y)
# extent : 0, 1, 0, 1 (xmin, xmax, ymin, ymax)
# coord. ref. : NA
# data source : in memory
# names : layer
# values : 3, 3 (min, max)
# Changing the first 5 values...
cob1[1:5] <- NA; cob2[1:5] <- NA; cob3[1:5] <- NA
overlay(cob1, cob2, cob3, fun=function(x1, x2, x3) (x1 + x2 + x3))
给出了相同的结果...
# but if I use `ifelse`, there is a problem:
overlay(cob1, cob2, cob3, fun=function(x1, x2, x3) ifelse(x1 > 0, x1 + x2 + x3, x3))
# Error in ifelse(x1, x1 + x2 + x3, x3) :
# argument "x2" is missing, with no default
# Another way to solve it is adding a useless extra variable without `NA`.
cob4 <- cob1d
overlay(cob1, cob2, cob3, cob4, fun=function(x1, x2, x3, x4) ifelse(x1 > 0, x1 + x2 + x3, x3))
# same result as before...
# class : RasterLayer
# dimensions : 6, 6, 36 (nrow, ncol, ncell)
# resolution : 0.1666667, 0.1666667 (x, y)
# extent : 0, 1, 0, 1 (xmin, xmax, ymin, ymax)
# coord. ref. : NA
# data source : in memory
# names : layer
# values : 3, 3 (min, max)
# or just avoiding the use of the `ifelse` function...
overlay(cob1, cob2, cob3, cob4, fun=function(x1, x2, x3, x4) (x1 > 0) * (x1 + x2 + x3) + (x1 <= 0)*x3)
【问题讨论】:
-
我遇到了同样的错误。不知道为什么...
-
您是否也在使用
ifelse函数?你能复制你正在使用的函数或它的简化版本吗? -
我刚刚试用了您的代码并收到了相同的错误消息。但是我真的不明白使用 ifelse 函数的这种奇怪行为