【发布时间】:2021-10-22 03:15:11
【问题描述】:
我想使用 terra R 包中的 aggregate 函数以分位数方法作为聚合函数聚合栅格。下面,我使用来自R base 的quantile 函数使用本地包目录中的栅格计算第50 个百分位数(即中位数)。我选择了第 50 个百分位数与中位数进行比较,但我的目标确实是计算其他分位数...
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()
我的电脑大约花了。 6秒做20次。
print(end_time-start_time)
时差 6.052727 秒
当我使用中值内置函数运行相同的 aggregate 运行时,它需要大约。执行相同的 20 次迭代的时间减少了 40 倍!
# 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)
0.1456101秒的时间差
由于我想计算第 50 位以外的其他百分位数,有人可以提供一些建议以加快 aggregate 在使用自定义函数时的速度吗?
【问题讨论】:
-
谷歌
"r fast quantile function".