我要做的是将数据存储在数据框或矩阵中。我正在每列上执行循环。以下是我的代码:
library(forecast)
#> Warning: package 'forecast' was built under R version 3.4.3
library(plyr)
library(data.table)
#> Warning: package 'data.table' was built under R version 3.4.2
# Create a list into a data frame
df <- iris
dfFitList <- lapply(df[, c(1:4)], forecast::auto.arima)
# Lets unpack the list to extract fitted values into a data frame
dfFitList <- lapply(dfFitList, '[', 'fitted')
dfFit <- as.data.frame.list(dfFitList)
colnames(dfFit) <- names(dfFitList)
# I want accuracy measures of each column in matrix or data frame
result <- result()
result <- vector("double", ncol(df))
for(i in 1:ncol(dfFit)){
result[i] <- accuracy(dfFit[,i], df[,i])
}
然而,我得到的是一个带有精度值列表的矢量。理想情况下,我想要得到的是一个矩阵(或数据框,可以是任何东西,列表也是如此),其中列作为我上面的dfFit数据框中的变量,行作为精度测量,反之亦然。如果有人能给我一个提示或建议,那将是伟大的,或者是一种避免循环的方法。
谢谢!
答案 0 :(得分:1)
只需将代码的最后一部分更改为
即可# I want accuracy measures of each column in matrix or data frame
result <- data.frame()
for(i in 1:ncol(dfFit)){
result <- rbind(result, accuracy(dfFit[,i], df[,i]))
}
这样你就得到了data.frame
> result
ME RMSE MAE MPE MAPE
Test set 0.04640401 0.5749977 0.4458530 0.005439232 7.492768
Test set1 -0.01435534 0.3643447 0.2775165 -1.831541188 9.410330
Test set2 0.05347604 0.5993159 0.3976608 -0.107065678 10.619752
Test set3 0.03005063 0.2744120 0.1905677 -4.529769486 22.043794
答案 1 :(得分:1)
或者没有循环:
result <- mapply(accuracy, dfFit, df[,1:4])
您将逐步获得(第一个是ME ..等等)。