I would like to use aggregate
function from the terra
R
package to aggregate raster with a quantiles approach as aggregation function. Here below, I used the quantile
function from R base
to compute 50th percentile (i.e. the median) using a raster from the local package directory. I chose the 50th percentile for comparison with median but my goal is indeed to compute other quantile(s)...
library(terra)
# load elevation coming with the terra pakage
r <- rast( system.file("ex/elev.tif", package="terra") )
plot(r)
# number of iteration
n_it <- 20
# with a custom function
start_time <- Sys.time()
for (i in 1:n_it){
ra <- aggregate(r, 2 , fun = function(x) quantile(x, probs = .5, na.rm = T))
}
end_time <- Sys.time()
It took my computer approx. 6 secs to do it 20 times.
print(end_time-start_time)
Time difference of 6.052727 secs
WHen I ran the same aggregate
run with the median built-in function, it took approx. 40 times less time to perform the very same 20 iterations!
# with a built-in function
start_time <- Sys.time()
for (i in 1:n_it){
ra <- aggregate(r, 2 , fun = median)
}
end_time <- Sys.time()
print(end_time-start_time)
Time difference of 0.1456101 secs
As I would like to compute other percentiles than the 50th, could someone provide some advises to speed up aggregate
when using custom functions?