Kquek
Kquek

Reputation: 57

map function in tidyverse language

I have the following formula

#Regression(Y1 - VTV)----
m1_vtv<-formula(vtv~retailsales)
m2_vtv<-formula(vtv~retailsales+cpi)
m3_vtv<-formula(vtv~retailsales+cpi+tmf)

#Regression(Y2 - VUG)----
m1_vug<-formula(vug~retailsales)
m2_vug<-formula(vug~retailsales+cpi)
m3_vug<-formula(vug~retailsales+cpi+tmf)

and I have added them into a list called regression_list

regression_list<-c(m1_vtv,m2_vtv,m3_vtv,m1_vug,m2_vug,m3_vug)

I am trying to glance() all the models in regression_list together. Individually it works:

tidy(model1) %>% as_tibble()
glance(model1)

enter image description here

However when I tried this

regression_list %>% 
  map(~lm(.x, data = df_final)) %>%
   map(~as_tibble(.x, data = df_final)) %>% 
  map(~glance(.x, data = df_final))

I get error message:

Error in as.data.frame.default(value, stringsAsFactors = FALSE) : cannot coerce class ‘"lm"’ to a data.frame

Looking for way to fit this into map function to run through all the formulas in regression_list

Upvotes: 1

Views: 253

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389047

As the error message says you are trying to convert lm object to tibble. You also don't need multiple map's as you can do this in the same map function. Try :

library(purrr)
library(broom)

result <- regression_list %>% map(~glance(lm(.x, data = df_final)))

If you want the result in one dataframe you can use map_df in place of map.

Upvotes: 1

Related Questions