Thornthwaite evapotranspiration on a raster datase

2019-08-20 08:35发布

问题:

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