Skip to content

Instantly share code, notes, and snippets.

@mikelove
Last active September 29, 2015 01:08
Show Gist options
  • Save mikelove/0e5ec11985a475a887a2 to your computer and use it in GitHub Desktop.
Save mikelove/0e5ec11985a475a887a2 to your computer and use it in GitHub Desktop.
# run linear model for each unique level of 'cyl' and return R^2
library(purrr)
mtcars %>%
split(.$cyl) %>%
map(~ lm(mpg ~ wt, data = .)) %>%
map(summary) %>%
map_dbl("r.squared")
# in base R this might look like
mtcars$cyl <- factor(mtcars$cyl)
sapply(levels(mtcars$cyl), function(cyl.lvl) {
fit <- lm(mpg ~ wt, data=mtcars[mtcars$cyl == cyl.lvl,])
summary(fit)[["r.squared"]]
})
@mikelove
Copy link
Author

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