Reputation: 11813
I'm trying to run models on different combinations of variables. I want to have a dataframe with 3 column: variables, p-value and r-square for each model. I'm using mtcars dataset as an example. Here are my codes:
c('wt', 'hp', 'qsec') %>%
combn(2, paste, collapse='*') %>%
structure(., names=.) %>%
map(~formula(paste('mpg~', .x))) %>%
map(lm, data=mtcars) %>%
map(~coef(summary(.x))[4,4]) %>%
unlist() %>%
data.frame(p.value=.) %>%
rownames_to_column(var='interaction')
Here is my output:
interaction p.value
1 wt*hp 0.0008108307
2 wt*qsec 0.2652596233
3 hp*qsec 0.0001411028
The question is how I can add another column to the dataframe after extracting r-square from each model? I want to achieve that in the chaining operation above. Since I hope to generalize the approach to other type of models, so I want to do that without using broom package. Appreciate it if anyone can help me with that. Thanks a lot.
Upvotes: 1
Views: 354
Reputation: 17299
I would try following
library(tidyverse)
reg.vars <- c('wt', 'hp', 'qsec')
tibble(interaction = combn(reg.vars, 2, paste, collapse = '*')) %>%
mutate(fit = map(interaction, ~ summary(lm(paste('mpg ~', .), data = mtcars))),
pval = map_dbl(fit, ~ coef(.)[4, 4]),
rsq = map_dbl(fit, ~ .$r.squared)) %>%
select(-fit)
# # A tibble: 3 x 3
# interaction pval rsq
# <chr> <dbl> <dbl>
# 1 wt*hp 0.0008108307 0.8847637
# 2 wt*qsec 0.2652596233 0.8340742
# 3 hp*qsec 0.0001411028 0.7854734
Upvotes: 5
Reputation: 887691
We can use broom
package functions like glance
, tidy
library(broom)
library(tidyverse)
v1 %>%
combn(2, paste, collapse='*') %>%
structure(., names=.) %>%
map(~summary(lm(formula(paste('mpg~', .x)), data = mtcars))) %>%
map(~ data.frame( tidy(.)[4,]['p.value'], glance(.)['r.squared'])) %>%
bind_rows(., .id = 'interaction')
# interaction p.value r.squared
#1 wt*hp 0.0008108307 0.8847637
#2 wt*qsec 0.2652596233 0.8340742
#3 hp*qsec 0.0001411028 0.7854734
v1 <- c('wt', 'hp', 'qsec')
Upvotes: 2