Based on this stackoverflow topic, I would like to extract coefficient.
From 'diamonds' dataset, I used nest() function to split diamonds dataset with respect to two categorical variables: color and cut. Then for each model compute coefficients and r_square and store them as data frames.
I successfully did it by these code:
df_dia <- diamonds %>% group_by(color, cut) %>% nest() %>% # generate summary mutate(fit = map(data, ~lm(price ~ carat, data=.)), summary= map(fit, glance)) %>% unnest(summary) %>% # generate coef mutate(fit = map(data, ~lm(price ~ carat, data=.) %>%coef %>% as.list %>% as_tibble)) %>% unnest(fit) %>% unnest(data) %>% select(color, cut, `(Intercept)`, carat, r.squared)
However, it is not efficient, since it has to do regression 2 times. Is there anybetter way?