我想将列通过管道传递到一个purrr::imap_dfr
使用自定义内部函数执行的函数中。
我的目标是df %>% diffmean(df, group, col1, col2)
运行t.test(col1 ~ group, .data = df)
并且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())
})
}
如果我只是在我想要分组的列中硬编码!!group
并且如果我切换出我想要选择的变量,则上面的代码有效!!!vars
。
我只是想让这个通用以供将来使用。
例如,使用diamonds
来自的数据集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())
})
产生:
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