Suppose I estimate a model where the dependent variable is \Delta(Y_t) = Y_t - Y_{t-1}.
So, I have the forecast for \Delta(Y_t^*). In a data.frame, I have the actual values of Y_t, and the \Delta(Y_t^*) forecasted. How can I create a new column of Y_t^*, where it combines the actual values and the forecasted values?
For example: level_actual is Y_t, diff_forecast is \Delta(Y_t^*) and the answer I am looking for is in answer_needed. See that the known Y_t substitutes the forecasted values, when it's known.
x <- data.frame(level_actual = c(1, 2, 3, 4, NA, NA, NA, NA, NA),
diff_forecast = c(1, 2, 0, 1, 2, 1, 0, 2, 1),
answer_needed = c(1, 2, 3, 4, 6, 7, 7, 9, 10))
I've try different ways, the most obvious one was:
x %>%
mutate(level_actual_forecast = level_actual,
level_actual_forecast = case_when(
!is.na(level_actual) ~ level_actual,
is.na(level_actual) ~ lag(level_actual_forecast) + diff_forecast
))
But it only find the very next value. How can I fill up the whole column?