【问题标题】:How to perform calculations on moving subsets of n elements of data frame without loop如何在没有循环的情况下对数据帧的 n 个元素的移动子集执行计算
【发布时间】: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


    【解决方案1】:

    rollapplyr 与指定的函数一起使用。如果您希望它在前 364 点中的工作时间少于 365 天,请将 fill=NA 替换为 partial=TRUE,或者如果您想放弃前 364 点,则省略两者。

    library(zoo)
    x <- 1:1000 # sample data
    ep <- rollapplyr(x, 365, function(x) sum(cumsum(x) / seq_along(x)), fill = NA)
    

    【讨论】:

    • 非常感谢,就是这样 :) 当然我必须做 rev(x) 。可惜我不能反馈这个答案:(
    • 没问题@Piotr。我可以做到:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-07
    • 2023-03-03
    • 2021-01-29
    • 1970-01-01
    相关资源
    最近更新 更多