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

applying function across multiple list in R

我有一个函数,我想调用 computeMASE 来应用于 3 个不同的列表 forecast.list,train.list,test.list 它们都有共同的值 (ap,wi)。我可以将函数单独用于列表,如下面的代码所示,但是当我使用 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)

mapply 的第一个参数应该是一个函数。您可以 "curry" 句点参数

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)