Reputation: 646
I'm trying to perform an function on a large data frame with 30+ features and I want to perform that using lapply and then extract the fitted values from the list it creates and put it into a data frame. Below is an example what I'm trying to do:
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))
Unfortunately the output is not quite what I want it to be. I want the names in the list, i.e. sepal.length, sepal.width, etc. to be the column names of my new data frame. Not fitted, fitted.1, fitted.2, etc. Does anyone have any suggestions to this?
Thanks!
Upvotes: 0
Views: 2225
Reputation: 4879
Is this the outcome you wanted?
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
Created on 2018-01-31 by the reprex package (v0.1.1.9000).
Upvotes: 1