Created
October 25, 2020 16:48
-
-
Save benzipperer/a20ccf3c245fa99b00f11f55e042dae0 to your computer and use it in GitHub Desktop.
calculate mean over various subgroups: Stata vs (tidy) R
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
| sysuse auto, clear | |
| local groups foreign headroom rep78 | |
| foreach x in `groups' { | |
| preserve | |
| rename `x' group_value | |
| collapse (mean) mean_mpg = mpg, by(group_value) | |
| gen group_name = "`x'" | |
| tempfile group`x' | |
| save `group`x'' | |
| restore | |
| } | |
| clear | |
| foreach x in `groups' { | |
| append using `group`x'' | |
| } | |
| order group_name group_value mean_mpg | |
| list |
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(tidyverse) | |
| mydata <- mtcars | |
| groups <- c("cyl", "gear", "carb") | |
| group_summarize <- function(x) { | |
| mydata %>% | |
| rename(group_value = {{ x }}) %>% | |
| group_by(group_value) %>% | |
| summarize(mean_mpg = mean(mpg)) %>% | |
| mutate(group_name = x) | |
| } | |
| map_dfr(groups, group_summarize) %>% | |
| select(group_name, group_value, mean_mpg) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment