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
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:
Here is the plot from my test run
I am not quite sure why this fails. Here is a workaround