我正在尝试在具有30多个功能的大型数据框架上执行功能,我想使用lapply执行该功能,然后从其创建的列表中提取拟合值并将其放入数据框中。以下是我正在尝试做的一个例子:
library(forecast)
library(plyr)
library(data.table)
# Create a list into a data frame
df <- iris
dfFitList <- lapply(df[,c(1:4)], auto.arima)
# Lets unpack the list to extract fitted values into a data frame
dfFitList <- lapply(dfFitList, '[','fitted')
dfFit <- as.data.frame.list(dfFitList, col.names = names(dfFitList))
不幸的是输出并不是我想要的。我希望列表中的名称,即sepal.length,sepal.width等,是我的新数据框的列名。没有安装,装,1,装,2等。有人对此有任何建议吗?
谢谢!
答案 0 :(得分:1)
这是你想要的结果吗?
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)
head(dfFit)
#> Sepal.Length Sepal.Width Petal.Length Petal.Width
#> 1 5.094900 3.496500 1.398600 0.1998000
#> 2 5.056164 3.379456 1.399999 0.1999999
#> 3 4.966164 3.241115 1.397144 0.1999999
#> 4 4.873511 3.220655 1.350723 0.2000000
#> 5 4.812726 3.216023 1.422147 0.2000000
#> 6 4.866759 3.308402 1.411775 0.2003662
由reprex package(v0.1.1.9000)于2018-01-31创建。