建立自己的for循环功能

时间:2019-04-18 09:58:00

标签: r for-loop forecasting

此代码通过预报包中的ets功能进行预报。

# CODE
library(forecast)
# Making data frame
DATA_SE T<-data.frame(TEST1 = c(200, 220, 200, 260, 300, 290, 320, 320, 360, 400, 300,     
                                300, 200, 250, 350, 390, 410, 440, 470, 350, 300, 320,
                                580, 450, 420, 550, 660, 270),
                      TEST2 = c(200, 220, 200, 260, 400, 290, 220, 370, 260, 200, 100, 
                                300, 500, 500, 450, 360, 400, 420, 470, 350, 340, 240, 
                                580, 550, 320, 550, 760, 370),
                      TEST3 = c(200, 220, 200, 260, 500, 290, 120, 240, 160, 400, 500, 500, 
                                400, 450, 350, 340, 490, 410, 470, 350, 300, 120, 580, 450, 
                                320, 250, 760, 670)
                )
#FOR LOOP
for(i in 1:ncol(DATA_SET)){
   # Build a ts for this column
   timeseries <- ts(DATA_SET[,i], start=c(2016,1), frequency = 12)
   # Build a foreacst based on the ts
   forecast <- ets(timeseries)

   # rename the forecast according to the original variable name
   colname <- colnames(DATA_SET)[i]
   forecastName <- paste("ETS_",colname," <- forecast",sep="")
   eval(parse(text = forecastName))
}

此代码的最终输出为三个列表:ETS_TEST1ETS_TEST2ETS_TEST3。因此,下一个陡峭的例子是这三个列表的并集,如下所示:

# Union of three list      
ETS_ALL <- mapply(ETS_TEST1, ETS_TEST2, ETS_TEST3, FUN = list, SIMPLIFY = FALSE)

所以我的问题是如何将该命令用于列表的并集,以较高的代码放入FOR LOOP的一部分中?

0 个答案:

没有答案