# How do I perform mathematic operations on raster data in R?

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)

library(terra)
library(geodata)
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
rowMeans(x)
}

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.