【发布时间】:2019-12-26 22:59:17
【问题描述】:
我正在尝试使用 R 计算有效干旱指数。需要这样做的众多步骤之一是计算蓄水量 (EP):
EP365=P1/1+(P1+P2)/2+(P1+P2+P3)/3+(P1+P2+P3+P4)/4+ … +(P1+…+P365)/365
其中 P1 是前一天的每日降水量,P2 是两天前的降水量,P365 是 365 天前的降水量。从第 1 天到第 365 天、第 2 天到第 366 天等,每 365 天必须计算 EP。
所以我有一个包含两列的数据框:日期和沉淀以及超过 20000 行。简单(且缓慢)的解决方案是计算从第 365 行到 nrow(df) 的 365 个元素的任何子集:
period_length <- 365
df$EP <- NA
for (i in (period_length:nrow(df))) {
first <- (i - period_length) + 1
SUB <- rev(df[first:i,]$prcp)
EP <- sum(cumsum(SUB)/seq_along(SUB))
df$EP[i] <- EP
}
Of course it works, however the question is how to calculate EP without using loop?
【问题讨论】:
标签: r