Skip to content

Instantly share code, notes, and snippets.

@benzipperer
Created October 25, 2020 16:48
Show Gist options
  • Select an option

  • Save benzipperer/a20ccf3c245fa99b00f11f55e042dae0 to your computer and use it in GitHub Desktop.

Select an option

Save benzipperer/a20ccf3c245fa99b00f11f55e042dae0 to your computer and use it in GitHub Desktop.
calculate mean over various subgroups: Stata vs (tidy) R
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
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