I downloaded a lot of WorldClim data, but there are some things that I wish to calculate that aren't given by WorldClim, like biotemperature and the aridity index. Biotemperature is definied by adding the mean temperature of each month, excluding months that have an average temperature below 0 degrees celsius, and dividing the sum by 12. Is there any way in R to do this using temperature data from WorldClim?


You can do mathematics with rasters with the usual mathematical operators.

There are assorted functions in the raster package for doing grouped functions, like monthly averages over stack of rasters.

There's also the terra package which works with rasters and should be faster than raster.


Install the geodata package to download some WorldClim data

# install.packages("remotes")
remotes::install_github("rspatial/geodata", dependencies=FALSE)

wc <- worldclim_country("Iceland",  "tavg", ".")

A fast and simple approach

bio1 <- mean( clamp(wc, 0, Inf) )

A more general, but slower, approach

biotemp <- function(x) {
    x[x < 0] <- 0

bio2 <- app(wc, biotemp)

A perhaps more direct approach is also possible

wc[wc < 0] <- 0
bio3 <- mean(wc)

This works fine small data sets that can be held in memory. But with larger datasets the performance deteriorates (perhaps even fails), especially with more involved computations as lots of temporary files may be created.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.