Skip to content

Instantly share code, notes, and snippets.

@mikelove
Last active April 7, 2023 16:30
Show Gist options
  • Save mikelove/0db5ae29c4e126f346a322f07fa55201 to your computer and use it in GitHub Desktop.
Save mikelove/0db5ae29c4e126f346a322f07fa55201 to your computer and use it in GitHub Desktop.
t-stat by group using tidyr::nest and purrr::map
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=.)
@mikelove
Copy link
Author

mikelove commented Apr 7, 2023

fct_relevel here is just to deal with the fact that t.test computes A - B but we usually want the reverse comparison

nest takes the columns we specify and converts them into a nested data.frame called data

after nest, the operations are within group, and map takes the data 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 of t.test

tidy cleans up fitted objects and turns them into tables

unnest them propagates the information back to the outer data.frame

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