I would like to pipe in columns into a function that performs a purrr::imap_dfr
with a custom inner function.
My goal is df %>% diffmean(df, group, col1, col2)
would run t.test(col1 ~ group, .data = df)
and t.test(col2 ~ group, .data = df
.
ttests <- function(df, group, ...) {
group <- rlang::ensym(group)
vars <- rlang::ensyms(...)
df %>%
dplyr::select(c(!!!vars)) %>%
purrr::imap_dfr(function(.x, .y) {
broom::tidy(t.test(.x ~ !!group)) %>%
dplyr::mutate(name = .y) %>%
dplyr::select(name, dplyr::everything())
})
}
The above code works if i simply hard code in the column I want to group on for !!group
and if I switch out the variables I want to select for with !!!vars
.
I just want to make this generic for future use.
For example, using the diamonds
dataset from ggplot2
:
diamonds <- diamonds %>%
dplyr::mutate(carat = carat > 0.25)
diamonds %>%
dplyr::select(depth, table, price, x, y, z) %>%
purrr::imap_dfr(., function(.x, .y) {
broom::tidy(t.test(.x ~ diamonds$carat)) %>%
dplyr::mutate(name = .y) %>%
dplyr::select(name, dplyr::everything())
})
Produces:
name estimate estimate1 estimate2 statistic p.value parameter conf.low conf.high method alternative
<chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <chr> <chr>
1 depth -0.247 61.5 61.8 -4.86 0.00000143 808. -0.347 -0.147 Welch Two Sample t-test two.sided
2 table 0.263 57.7 57.5 3.13 0.00183 805. 0.0977 0.427 Welch Two Sample t-test two.sided
3 price -3477. 506. 3983. -197. 0 51886. -3512. -3443. Welch Two Sample t-test two.sided
4 x -1.77 3.99 5.76 -299. 0 6451. -1.78 -1.76 Welch Two Sample t-test two.sided
5 y -1.75 4.01 5.76 -290. 0 6529. -1.76 -1.73 Welch Two Sample t-test two.sided
6 z -1.10 2.46 3.55 -294. 0 6502. -1.10 -1.09 Welch Two Sample t-test two.sided