Reputation: 1159
I have a function that I would like called computeMASE
to apply to 3 different lists forecast.list,train.list,test.list
all of them have common values (ap
,wi
). I can use the function individually to the list as shown in the code below, but when I use the lapply
and apply the function to get the data all at once, I'm unable to do. Please see below for a reproducible example. Please let me know how to solve this.
Many Thanks
library("forecast")
## Forecast Function
for.x <- function(x){
fc <- forecast(ets(x),h=18)$mean
return(fc)
}
## MASE Function
computeMASE <- function(forecast,train,test,period){
# forecast - forecasted values
# train - data used for forecasting .. used to find scaling factor
# test - actual data used for finding MASE.. same length as forecast
# period - in case of seasonal data.. if not, use 1
forecast <- as.vector(forecast)
train <- as.vector(train)
test <- as.vector(test)
n <- length(train)
scalingFactor <- sum(abs(train[(period+1):n] - train[1:(n-period)])) / (n-period)
et <- abs(test-forecast)
qt <- et/scalingFactor
meanMASE <- mean(qt)
return(meanMASE)
}
## Prepare Data
train.list <- list(ap = ts(AirPassengers[1:(length(AirPassengers)-18)],start=start(AirPassengers),frequency=12),
wi = ts(wineind[1:(length(wineind)-18)],end=end(wineind),frequency=12))
test.list <- list(ap = ts(AirPassengers[(length(AirPassengers)-17):length(AirPassengers)],end=end(AirPassengers),frequency=12),
wi = ts(wineind[(length(wineind)-17):length(wineind)],end=end(wineind),frequency=12))
## Create Forecast
forecast.list <- lapply(train.list,for.x)
## Compute MASE for each list in the forecast
k.ap <- computeMASE(forecast.list$ap,train.list$ap,test.list$ap,12)
k.wi <- computeMASE(forecast.list$wi,train.list$wi,test.list$wi,12)
## How to apply compute MASE to all the elements in the list,? below does not work
mapply(computeMASE(X,Y,Z,12),X=forecast.list,Y=train.list,Z=test.list)
Upvotes: 3
Views: 6153
Reputation: 26446
The first argument of mapply
should be a function. You can "curry" the period argument
mapply(function(x,y,z) computeMASE(x,y,z,12), forecast.list, train.list, test.list)
or, provide it as another argument (with implicit recycling)
mapply(computeMASE, forecast.list, train.list, test.list, 12)
Upvotes: 7