Skip to content

Instantly share code, notes, and snippets.

@jsta
Last active April 12, 2021 16:50
Show Gist options
  • Save jsta/07f2476b37ff0a0d74f218623720044d to your computer and use it in GitHub Desktop.
Save jsta/07f2476b37ff0a0d74f218623720044d to your computer and use it in GitHub Desktop.
purrr and non-purrr code comparison
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)
}))
@jsta
Copy link
Author

jsta commented Mar 31, 2021

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment