将列表转换为数据框。 auto.arima 函数的一个例子

convert list into a data frame. A case of auto.arima function

我的时间序列必须使用 auto.arima 函数进行校正。我获得了结果,但我在 整理数据 时遇到了问题。要重现该问题,我将使用以下数据框。

df <- data.frame(
  stringsAsFactors = FALSE,
            Season = c("Winter 1996-1997",
                       "Summer 1997","Winter 1997-1998","Summer 1998","Winter 1998-1999",
                       "Summer 1999","Winter 1999-2000","Summer 2000",
                       "Winter 2000-2001","Summer 2001","Winter 2001-2002",
                       "Summer 2002","Winter 2002-2003","Summer 2003",
                       "Winter 2003-2004","Summer 2004","Winter 2004-2005","Summer 2005",
                       "Winter 2005-2006","Summer 2006","Winter 2006-2007",
                       "Summer 2007","Winter 2007-2008"),
            France = c(33.83,65.51,26.41,30.86,
                       39.77,23.71,37.67,35.66,39.45,37.49,29.28,51.38,
                       35.93,33.33,24.01,36.03,26.45,16.48,25.72,39.93,41.8,
                       29.31,32.79),
           Germany = c(27.06,35.93,28.92,21.65,
                       25.72,39.93,16.48,33.34,35.39,27.04,25.53,27.06,
                       35.93,28.92,21.65,40.93,18.55,42.34,17.29,21.8,34.95,
                       25.02,29.92),
             Spain = c(42.26,32.91,27.91,19.06,
                       17.29,21.8,16.48,33.34,35.39,26.74,23.68,42.26,32.91,
                       27.91,19.06,38.69,15.02,60.2,16.56,28.72,26.37,
                       22.92,26.88),
        Luxembourg = c(NA,NA,NA,NA,16.56,28.72,
                       16.73,41.81,31.91,27.25,29.75,48.36,24.26,26.24,
                       18.82,33.41,17.56,69.72,17.68,23.08,40.39,22.3,
                       35.61))
library(forecast)

#run auto.arima function and unlist the results in a data frame
library(forecast)
Auto_arima_results <- as.data.frame(do.call(rbind, lapply(df[-1], auto.arima)))

#obtain only the fitted values
Auto_arima_fitted_values <-  Auto_arima_results %>% select(contains("fitted"))

我最终得到以下结果:

但我想获得的是一个数据框,其中:

a) 第 1 列是季节
b) 第 2 至 4 列是国家(法国、德国、西班牙和卢森堡)
c) 这些国家的值是我从 arima 函数获得的 拟合 值。

如有任何帮助,我们将不胜感激

您只能从输出中提取 fitted 个值。

library(forecast)

result <- cbind(df[1],do.call(cbind, 
              lapply(df[-1], function(x) as.numeric(auto.arima(x)$fitted))))

#             Season   France  Germany    Spain Luxembourg
#1  Winter 1996-1997 34.46957 28.32021 28.45043   28.84253
#2       Summer 1997 34.46957 30.28881 28.45043   35.91868
#3  Winter 1997-1998 34.46957 23.79553 28.45043   30.73889
#4       Summer 1998 34.46957 25.44389 28.45043   35.84627
#5  Winter 1998-1999 34.46957 34.24603 28.45043   25.16294
#6       Summer 1999 34.46957 34.21670 28.45043   29.38004
#7  Winter 1999-2000 34.46957 21.22659 28.45043   31.36506
#8       Summer 2000 34.46957 33.50654 28.45043   30.30014
#....
#....
#....