## Pages

### Speeding up mean and standard deviation calculation for a stack of rasters in R

While modelling the distribution of invasive seaweeds during my PhD I wanted to calculate the mean and standard deviation of a set of SDMs that appeared to be equivalent in for the current climate but who gave different results for the future climate. However, the standard naive approach for calculating the mean and standard deviation of a RasterStack was rather slow. I managed to get a 20 fold speed up by calculating the mean and standard deviation by aggregating them in a stream. This rather obvious for calculating the mean, summing all rasters and then dividing by the number of rasters. For the standard deviation, the formula is only slightly more complicated and can be found both on Wikipedia and in code on StackOverflow. If your raster contains very large numbers, you might need to adapt this code to use Welford's method.

`# Option 1: shorter but slower`
```rasterstack_meansd_slow <- function(x) {
mean <- raster::mean(x)
sd <- raster::calc(x, sd)```
`  list(mean=mean, sd=sd)`
```}

# Option 2: faster but more code
rasterstack_meansd_fast <- function(x) {
s0 <- nlayers(x)
s1 <- raster(x, layer=1)
s2 <- s1^2
for(ri in 2:s0) {
r <- raster(x, layer=ri)
s1 <- s1 + r
s2 <- s2 + r^2
}
list(mean=s1/s0, sd=sqrt((s0 * s2 - s1 * s1)/(s0 * (s0 - 1))))
}
```

As a small example I calculate the mean and standard deviation of the sea surface temperature for different climate scenarios for 2050. The fast version only takes 10 seconds on my machine while the slow version takes 225 seconds to calculate the mean and standard deviation.

```library(sdmpredictors)

'BO2_RCP60_2050_tempmean_ss', 'BO2_RCP85_2050_tempmean_ss'))

system.time({ fast <- rasterstack_meansd_fast(sstfuture) }) # 10 seconds
system.time({ slow <- rasterstack_meansd_slow(sstfuture) }) # 225 seconds
```
{"ft_lang_label":"__label__en","ft_lang_prob":0.6887278,"math_prob":0.97573817,"size":1218,"snap":"2021-43-2021-49","text_gpt3_token_len":364,"char_repetition_ratio":0.11532125,"word_repetition_ratio":0.011173184,"special_character_ratio":0.33415434,"punctuation_ratio":0.115384616,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.99717647,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2021-10-25T06:21:07Z\",\"WARC-Record-ID\":\"<urn:uuid:e51cc61a-bff6-4050-9804-7c2c7e8ce591>\",\"Content-Length\":\"73169\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:dfb17976-6ec8-4aff-a6f4-e9ee79136b9e>\",\"WARC-Concurrent-To\":\"<urn:uuid:a1c80528-5e78-492f-ab7c-1ea8f4d74ef9>\",\"WARC-IP-Address\":\"172.217.1.211\",\"WARC-Target-URI\":\"http://www.samuelbosch.com/2018/02/speeding-up-mean-and-standard-deviation.html\",\"WARC-Payload-Digest\":\"sha1:LWUQFJHERA4TMIATOCDKYCOUM4E2SFCY\",\"WARC-Block-Digest\":\"sha1:MVCHDSCU44ST7CQZW6SVJWEM5VPEHW3U\",\"WARC-Identified-Payload-Type\":\"application/xhtml+xml\",\"warc_filename\":\"/cc_download/warc_2021/CC-MAIN-2021-43/CC-MAIN-2021-43_segments_1634323587655.10_warc_CC-MAIN-20211025061300-20211025091300-00611.warc.gz\"}"}