Thornthwaite 栅格数据集上的蒸散量。误差公式未矢量化

问题描述 投票:0回答:2

我正在尝试使用 SPEI 包中包含的 Thornthwaite ET 公式计算在栅格数据集上运行 SPEI 的蒸散量 (ET)

这是我的代码

library(SPEI)
library(raster)
library(zoo)

tm = array(1:(3*4*12*64),c(3,4,12*64))
tm = brick(tm)

dates=seq(as.Date("1950-01-01"), as.Date("2013-12-31"), by="month")
tm<- setZ(tm,dates)
names(tm) <- as.yearmon(getZ(tm))

thornthwaite ET
th <- function(Tave, lat) {
  SPEI::thornthwaite(Tave, lat)
} 

lat <- setValues(a, coordinates(tm)[, "y"])
out <- raster::overlay(tm, lat, fun = th)

但我收到以下错误:

Error in (function (x, fun, filename = "", recycle = TRUE, forcefun = FALSE,  : 
  cannot use this formula, probably because it is not vectorized

请问您能帮忙吗?

感谢一百万

r overlay raster r-raster calc
2个回答
1
投票

我不太清楚为什么会失败。这是一个解决方法

library(SPEI)
library(raster)
library(zoo)

tm = array(20,c(3,4,12*64))
tm = brick(tm)

dates=seq(as.Date("1950-01-01"), as.Date("2013-12-31"), by="month")
tm<- setZ(tm,dates)
names(tm) <- as.yearmon(getZ(tm))

#thornthwaite ET
th <- function(Tave, lat) {
    as.vector(SPEI::thornthwaite(as.vector(Tave), lat))
} 

a <- raster(tm)
lat <- init(a, "y")
#out <- raster::overlay(tm, lat, fun = th)
out <- brick(tm, values=FALSE)

for (i in 1:ncell(tm)) {
    out[i] <- th(tm[i], lat[i])
}

0
投票

需要再执行一个步骤才能在 raster::overlay 中完成此操作。正如错误消息所建议的那样,这就是“矢量化”函数。 Vectorize 是一个基本函数,它为给定函数创建一个包装器以与 mapply 一起使用。

请看下面的代码:

library(raster)
library(zoo)

tm = array(1:(3*4*12*64),c(3,4,12*64))
tm = brick(tm)

dates=seq(as.Date("1950-01-01"), as.Date("2013-12-31"), by="month")
tm<- setZ(tm,dates)
names(tm) <- as.yearmon(getZ(tm))

#thornthwaite ET
th <- function(Tave, lat) {
  as.vector(SPEI::thornthwaite(as.vector(Tave), lat))
} 

lat <- init(raster(tm), "y")

## now run overlay with Vectorize in the function call
out <- overlay(tm, lat, fun = Vectorize(th))

plot(out)

Here is the plot from my test run

© www.soinside.com 2019 - 2024. All rights reserved.