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