汇总一列的前X行?

时间:2018-11-05 19:50:37

标签: r

我有一个代码,在其中对值的前几行进行检查,以计算coverage值。我有以下代码示例:

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)) 

问题是,主导价值要大得多,我必须通过一系列ifelses来实现多个公式。我有办法得到这部分的结果吗?

(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)),

不使用一系列班次吗?

1 个答案:

答案 0 :(得分:2)

shift是向量化的,因此您可以为其提供n的向量,然后将结果与Reduce('+', ...)

相加
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

您也可以使用zoo:rollsum

library(zoo)
d <- 
with(df, 
  rollsum(c(variable_predicted[-1], rep(0, 3)), 3))

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