Last active
April 12, 2021 16:50
-
-
Save jsta/07f2476b37ff0a0d74f218623720044d to your computer and use it in GitHub Desktop.
purrr and non-purrr code comparison
This file contains hidden or 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(purrr) | |
library(dplyr) | |
library(broom) | |
mtcars %>% | |
split(.$cyl) %>% # from base R | |
map(~ lm(mpg ~ wt, data = .)) %>% | |
map(summary) %>% | |
map_dbl("r.squared") | |
unlist(lapply(unique(mtcars$cyl), function(x){ | |
dt <- dplyr::filter(mtcars, cyl == x) | |
fit <- lm(mpg ~ wt, data = dt) | |
fit %>% | |
broom::glance() %>% | |
pull(r.squared) %>% | |
setNames(x) | |
})) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In the one case
map
is obscuring a lot of operations. In the other, we have logically grouped commands and it is very clear what is being iterated on.