Last active
August 20, 2020 19:44
-
-
Save datalorax/6486419176374e4366b89534e52e6568 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(tidyverse) | |
by_species <- iris %>% | |
group_by(Species) %>% | |
nest() | |
specific_models <- tibble( | |
Species = unique(iris$Species), | |
model = list(function(d) lm(Sepal.Length ~ Petal.Width + Petal.Length, d), | |
function(d) lm(Sepal.Length ~ Petal.Width, d), | |
function(d) lm(Sepal.Length ~ Sepal.Width + Petal.Length, d)) | |
) | |
left_join(by_species, specific_models) %>% | |
mutate(fit = map2(model, data, ~.x(.y)), | |
fit = map(fit, broom::tidy)) %>% | |
select(Species, fit) %>% | |
unnest(fit) | |
# # A tibble: 8 x 6 | |
# # Groups: Species [3] | |
# Species term estimate std.error statistic p.value | |
# <fct> <chr> <dbl> <dbl> <dbl> <dbl> | |
# 1 setosa (Intercept) 4.247508 0.4114336 10.32368 1.134052e-13 | |
# 2 setosa Petal.Width 0.7121346 0.4874038 1.461077 1.506479e- 1 | |
# 3 setosa Petal.Length 0.3989790 0.2957742 1.348931 1.838227e- 1 | |
# 4 versicolor (Intercept) 4.044640 0.4229151 9.563717 1.068715e-12 | |
# 5 versicolor Petal.Width 1.426365 0.3155204 4.520673 4.035422e- 5 | |
# 6 virginica (Intercept) 0.6247824 0.5248675 1.190362 2.398819e- 1 | |
# 7 virginica Sepal.Width 0.2599540 0.1533376 1.695305 9.663372e- 2 | |
# 8 virginica Petal.Length 0.9348189 0.08960197 10.43302 8.009442e-14 | |
# Or for the same output with dplyr 1.0 syntax | |
left_join(by_species, specific_models) %>% | |
rowwise() %>% | |
summarize(fit = list(model(data)), | |
fit = list(broom::tidy(fit))) %>% | |
unnest(fit) | |
# or even more directly | |
left_join(by_species, specific_models) %>% | |
rowwise() %>% | |
summarize(model(data) %>% broom::tidy()) | |
# it's also poosible to model for subgroup combinations, which isn't | |
# particularly helpful in this case, but could be in others (e.g., effect size calcs) | |
left_join(by_species, specific_models, by = character()) %>% | |
rowwise() %>% | |
summarize(model(data) %>% broom::tidy()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment