Last active
April 7, 2023 16:30
-
-
Save mikelove/0db5ae29c4e126f346a322f07fa55201 to your computer and use it in GitHub Desktop.
t-stat by group using tidyr::nest and purrr::map
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(dplyr) | |
library(ggplot2) | |
library(tidyr) | |
library(purrr) | |
library(broom) | |
library(forcats) | |
d <- data.frame( | |
value = rnorm(24), | |
type = factor(rep(c("A","B"), c(5,3))), | |
group = rep(1:3, each=8), | |
group_var = rep(rnorm(3), each=8) | |
) | |
d %>% | |
ggplot(aes(type, value)) + | |
geom_boxplot() + | |
facet_wrap(~ group) | |
d %>% | |
mutate(type = fct_relevel(type, "B", "A")) %>% | |
nest(data = c(type, value)) %>% | |
mutate(ttest = map(data, ~t.test(value ~ type, data=.)), | |
tstat = map(ttest, tidy)) %>% | |
unnest(tstat) %>% | |
select(group, group_var, statistic) | |
# manually (note that t-test usually does A - B, but we want B - A) | |
d %>% | |
filter(group == 1) %>% | |
t.test(value ~ type, data=.) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
fct_relevel
here is just to deal with the fact thatt.test
computes A - B but we usually want the reverse comparisonnest
takes the columns we specify and converts them into a nested data.frame calleddata
after nest, the operations are within group, and
map
takes thedata
and applies the function in the second argument to make a new column in the outer data.frame. the columns in the outer data.frame can be complex objects like the result oft.test
tidy
cleans up fitted objects and turns them into tablesunnest
them propagates the information back to the outer data.frame