Sum the leading X rows of a column?

992 views r
3

I have a code where I run a check on the leading rows of a value, in order to calculate a coverage value. I have a sample of the code below:

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

the thing is, the leading value is much larger and I have to do this in a series of ifelses for multiple formulas. Is there a way for me to get the result of this part:

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

without using a series of shifts?

answered question

1 Answer

8

shift is vectorized, so you can give it a vector for n, and then add the results together with 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

posted this

Have an answer?

JD

Please login first before posting an answer.