在R中的多个列表中应用函数

时间:2016-03-11 18:49:49

标签: r lapply sapply mapply

我有一个函数,我想将computeMASE应用于3个不同的列表forecast.list,train.list,test.list,所有列表都有共同的值(apwi)。我可以单独使用该功能列表,如下面的代码所示,但当我使用lapply并应用函数同时获取数据时,我无法做到。请参阅下面的可重现示例。请让我知道如何解决这个问题。

非常感谢

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)

1 个答案:

答案 0 :(得分:2)

mapply的第一个参数应该是一个函数。你可以&#34;咖喱&#34;期间论点

mapply(function(x,y,z) computeMASE(x,y,z,12), forecast.list, train.list, test.list)

或者,将其作为另一个参数(隐式回收)

mapply(computeMASE, forecast.list, train.list, test.list, 12)