Thornthwaite evapotranspiration on a raster dataset . Error formula not vectorised

浪子不回头ぞ 提交于 2020-01-06 06:00:08

问题


I am trying to calculate evapotranspiration (ET) for running SPEI on a raster dataset by using the Thornthwaite ET formula included in the SPEI package

this is my code

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)

but i got the following error:

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

Please can you help?

Thanks a million


回答1:


I am not quite sure why this fails. Here is a workaround

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])
}



回答2:


One more step is required to make this work within raster::overlay. That is "Vectorizing" the the function, as was suggested by the error message. Vectorize is a base function that creates a wrapper for the given function to work with mapply.

Please see the code below:

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



来源:https://stackoverflow.com/questions/50452135/thornthwaite-evapotranspiration-on-a-raster-dataset-error-formula-not-vectoris

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!