r 栅格无法获得 if else 逻辑来处理常量变量
r raster can't get if else logic to work with variable that is a constant
我正在尝试对我的光栅块执行一些条件逻辑。在下面的代码中 myFun1
正确生成 raster.out1
。但是 myFun2
在尝试生成 raster.out2
时会产生错误。错误信息是
Error in which(test) : argument to 'which' is not logical
除了使用值为 5 的变量外,这两个函数看起来完全相同。我显然遗漏了一些东西。
library(raster)
raster.in <- raster(nrows=100, ncols=100)
raster.in[] <- runif(ncell(raster.in), min = -10, max = 10)
const1 <- 5
myFun1 <- function(x, ...) {
ifelse(x <= 5, 5, x )
}
raster.out1 <- calc(raster.in, fun = myFun1)
myFun2 <- function(x, tbase, ...) {
ifelse(x <= tbase, tbase, raster.in)
}
raster.out2 <- calc(raster.in, fun = myFun2(x = raster.in, tbase = const1))
两个问题,你的函数中应该有 x
而不是 raster.in
,并且要放置一个带有多个参数的函数你需要一些额外的代码:
myFun2 <- function(x, tbase, ...) {
ifelse(x <= tbase, tbase, x)
}
calc(raster.in, function(x){myFun2(x, tbase = const1)})
astrofunkswag 的回答是正确的,但有更直接的方法可以通过 clamp
或 reclassify
获得您想要的内容
r1 <- clamp(raster.in, const1)
r2 <- reclassify(raster.in, cbind(-Inf, const1, const1))
还有一个隐藏的(效率较低的)ifel 方法
r3 <- raster:::.ifel(raster.in < const1, const1, raster.in)
我正在尝试对我的光栅块执行一些条件逻辑。在下面的代码中 myFun1
正确生成 raster.out1
。但是 myFun2
在尝试生成 raster.out2
时会产生错误。错误信息是
Error in which(test) : argument to 'which' is not logical
除了使用值为 5 的变量外,这两个函数看起来完全相同。我显然遗漏了一些东西。
library(raster)
raster.in <- raster(nrows=100, ncols=100)
raster.in[] <- runif(ncell(raster.in), min = -10, max = 10)
const1 <- 5
myFun1 <- function(x, ...) {
ifelse(x <= 5, 5, x )
}
raster.out1 <- calc(raster.in, fun = myFun1)
myFun2 <- function(x, tbase, ...) {
ifelse(x <= tbase, tbase, raster.in)
}
raster.out2 <- calc(raster.in, fun = myFun2(x = raster.in, tbase = const1))
两个问题,你的函数中应该有 x
而不是 raster.in
,并且要放置一个带有多个参数的函数你需要一些额外的代码:
myFun2 <- function(x, tbase, ...) {
ifelse(x <= tbase, tbase, x)
}
calc(raster.in, function(x){myFun2(x, tbase = const1)})
astrofunkswag 的回答是正确的,但有更直接的方法可以通过 clamp
或 reclassify
r1 <- clamp(raster.in, const1)
r2 <- reclassify(raster.in, cbind(-Inf, const1, const1))
还有一个隐藏的(效率较低的)ifel 方法
r3 <- raster:::.ifel(raster.in < const1, const1, raster.in)