R 对列的前导X行求和?

R 对列的前导X行求和?,r,R,我有一个代码,其中我对值的前导行进行检查,以计算覆盖率值。我有以下代码示例: library(data.table) df <- data.frame( dept = c(rep('FIREDEPT', 5), rep('WATERDEPT', 5)), month = 201808:201812, initial_stock = sample(75884:85347, 10), variable_predicted = sample(50000:100000, 10))

我有一个代码,其中我对值的前导行进行检查,以计算覆盖率值。我有以下代码示例:

library(data.table)

df <- data.frame(
  dept = c(rep('FIREDEPT', 5), rep('WATERDEPT', 5)),
  month = 201808:201812,
  initial_stock = sample(75884:85347, 10),
  variable_predicted = sample(50000:100000, 10))


df <- mutate(df, calculation = ifelse(initial_stock <= (shift(variable_predicted, type="lead", fill = 0)
                                                        + shift(variable_predicted, type="lead", fill = 0, n = 2)
                                                        + shift(variable_predicted, type="lead", fill = 0, n = 3)),
                                      (3 + (initial_stock 
                                            - shift(variable_predicted, type="lead", fill = 0) 
                                            - shift(variable_predicted, type="lead", fill = 0, n = 2)
                                      ) / shift(variable_predicted, type="lead", fill = 0, n = 3)) * 30,
                                      0)) 

在不使用一系列移位的情况下?

shift
是矢量化的,因此您可以给它一个
n
的向量,然后将结果与
Reduce(“+”,…)


非常感谢。我对Reduce不熟悉。
(shift(variable_predicted, type="lead", fill = 0)
  + shift(variable_predicted, type="lead", fill = 0, n = 2)
  + shift(variable_predicted, type="lead", fill = 0, n = 3)),
a <- 
with(df,
     (shift(variable_predicted, type="lead", fill = 0)
  + shift(variable_predicted, type="lead", fill = 0, n = 2)
  + shift(variable_predicted, type="lead", fill = 0, n = 3)))

b <- 
with(df,
     Reduce(`+`, shift(variable_predicted, n = 1:3, fill = 0, type = 'lead')))


identical(a, b)
# [1] TRUE
library(zoo)
d <- 
with(df, 
  rollsum(c(variable_predicted[-1], rep(0, 3)), 3))

all.equal(a, d)
# [1] TRUE