0

Create a function that takes in a numeric vector. The objective is to forecast using exponential smoothing.

The formula is ( is the actual value and ̂ is the forecasted value) - ̂+1=̂+(− ̂)

The output of the function should be a data frame with two columns – actual and predicted values. Set a default value of 0.8 for .

ExpForecast = function(v,alpha = 0.8)
{
ResultMatrics1 = data.frame()
for (i in 2:length(v))
{

       a = data.frame(v[i],(ResultMatrics1[(i-1),2]))
                     +alpha*(v[(i-1)]-ResultMatrics1[(i-1),2])
   ResultMatrics1 = rbind(ResultMatrics1,a)
}
return(ResultMatrics1)
colnames(ResultMatrics1) = c("y","y_hat")
}

ExpForecast(v=c(2,5,13,24,53))

Everytime, R gives me " Error in data.frame(v[i], (ResultMatrics1[(i - 1), 2])) : arguments imply differing number of rows: 1, 0 ". Can anyone know what's wrong?

SeanZ
  • 17
  • 5
  • You cannot do recursive calculations this way. v [i-1] is not defined. You should look into filter function: http://stackoverflow.com/questions/14372880/simple-examples-of-filter-function-recursive-option-specifically – keiv.fly Feb 26 '17 at 20:04
  • Whether `v[i-1,]` is defined is not the (biggest) issue, I think the problem is with `ResultMatrics1[(i-1),2]`, both because the `(i-1)`th row does not exist when `i` is 2, and it has no columns (since you defined it with none). – r2evans Feb 26 '17 at 21:19
  • Do you know how to fix it? The reason I did this is to keep the predicted value and the actual value of the first row the same. – SeanZ Feb 26 '17 at 22:08

0 Answers0