In excel I can have the the following format:
alpha .10
time Demand Forecast
1 10 50 50
2 11 75
3 12 65
4 13 90
5 14 120
where in the forecast column I would apply simple exponential smoothing to forecast the second period
[(alpha * 75) + (1- alpha)*(50)]
repeating this process to obtain the additional forecast
[(alpha * next demand) + (1- alpha)*(previous forecast)]
to obtain the 3 - 6th period forecasts.
In R when I try using the forecast package it keeps forecasting for periods 6 and beyond which is not what I want the code I used was:
fore3 <- ses(fore, h = 9, alpha = 0.1)
with dplyr
I tried the following:
fore3 <- mutate(fore, Forecast = (alpha * Demand) + lag(Forecast * (1-alpha)))
but end up with
time Demand Forecast
1 10 50 50
2 11 75 NA
3 12 65 NA
4 13 90 NA
5 14 120 NA
Exponentially weighted moving averages are easily implemented with Reduce
with acc=TRUE
ewma<-function(x,alpha) Reduce(function(y,xi) y*(1-alpha)+xi*alpha,x,acc=TRUE)
The first argument of Reduce
is a function that describes the current step. This should look similar to your function. Specifying acc=TRUE
just instructs Reduce
to keep the results of each application of the steps. This is analogous to writing a formula in Excel that refers to the previous cell and an adjacent input and dragging the formula down.
ewma(Demand,0.1)
#> [1] 50.0000 52.5000 53.7500 57.3750 63.6375
I'm not entirely sure what you want, but I think you want to apply your function iteratively? How big is your time series? You could use a for loop as follows:
alpha <- 0.1
forecast <- function(x) (alpha * 75) + (1-alpha) * x
periods <- 5
forecast.vector <- 50
for (i in 1:periods) {
forecast.vector[i + 1] <- forecast(forecast.vector[i])
}
forecast.vector
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.