user3374236
user3374236

Reputation: 67

Merge multiple rasters into one final raster by averaging for all points

I'm working on many rasters to get one final raster to represent the average level.

I've 365 continuous rasters: each raster represents the daily tempeature in a region. One raster to be generated: to average daily values of 365 rasters to reflect the temperature level within a year.

I'm not sure if the code below is correct or not?

temperature_average<- calc(h, mean) ## h is a stack of 365 rasters (daily temperature) in 2020

Is there a way to reaching this purpose? Much appreciated for any guidance.

Upvotes: 2

Views: 1206

Answers (1)

Elia
Elia

Reputation: 2584

there are different ways for doing raster algebra, with packages raster and terra (which is the recommended package for raster calculation and manipulation). See the benchmark below

library(raster)
library(terra)
#toy data
r <- raster(ncol=36, nrow=18, vals=1:(18*36))
s <- stack(r,r*0.5,r/3,sin(r))
#convert raster to SpatRaster from terra package
t <- rast(s)

#raster::calc
temperature_average<- calc(s, mean)
#raster::mean
temperature_average2 <- mean(s)
#terra::app
temperature_average3 <- app(t,mean)
#terra::mean
temperature_average4 <- mean(t)
#see which is the fastes
library(microbenchmark)
microbenchmark("calc"=temperature_average<- calc(s, mean),
               "raster::mean"=temperature_average2 <- mean(s),
               "app"=temperature_average3 <- app(t,mean),
               "terra::mean"=temperature_average5 <- mean(t))

Unit: milliseconds
         expr    min      lq     mean  median      uq     max neval cld
         calc 2.8666 2.95185 3.336269 3.02475 3.10360 17.6321   100   c
 raster::mean 2.3398 2.39725 2.842573 2.44095 2.49595 32.4901   100  bc
          app 1.5573 1.59200 1.859306 1.63535 1.71005 20.6778   100 a  
  terra::mean 1.8386 1.88065 2.243889 1.94090 2.02975 21.0170   100 ab 

As you can see terra::app is the fastest, followed by terra::mean

Upvotes: 1

Related Questions