Is there a faster way for calculating median of rasterstack in r?

Viewed 272

I am calculating some rasterstatistics on an rasterstack, what is really big.

Is there a faster way for calculating a median for example. I know I can parallelize my calculation but I am looking for a faster function or something.

This is my code:

r_median <- calc(rasterstack, fun=median, na.rm=TRUE)

Thanks

2 Answers

With terra (as suggested by E.B.) which is much faster than raster, you can use median

Example data

library(terra)
s <- rast(system.file("ex/logo.tif", package="terra"))   
ss <- c(0.5 * sqrt(s), sqrt(s), s)

Solution

m <- median(ss)
m
#class       : SpatRaster 
#dimensions  : 77, 101, 1  (nrow, ncol, nlyr)
#resolution  : 1, 1  (x, y)
#extent      : 0, 101, 0, 77  (xmin, xmax, ymin, ymax)
#coord. ref. : +proj=merc +lon_0=0 +k=1 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs 
#data source : memory 
#names       :   median 
#min values  :        0 
#max values  : 15.96872 

plot(m)

And more generally (but slower), you can use app with any summarizing function

x <- app(ss, median) 

Unfortunately not one that will work consistently, imho. However, a new package to replace raster is under way and seems significantly faster while keeping most of the same syntax and fornalism: https://github.com/rspatial/terra

/E

Related