# \donttest{
library(dplyr, warn.conflicts = FALSE)
library(stringr)
# Example 1 ----------------------------------
# fn returns t-test pvalue
my_ttest <- function(data, variable, by, ...) {
t.test(data[[variable]] ~ as.factor(data[[by]]))$p.value
}
add_stat_ex1 <-
trial %>%
select(trt, age, marker) %>%
tbl_summary(by = trt, missing = "no") %>%
add_stat(fns = everything() ~ my_ttest) %>%
modify_header(
list(
add_stat_1 ~ "**p-value**",
all_stat_cols() ~ "**{level}**"
)
)
# Example 2 ----------------------------------
# fn returns t-test test statistic and pvalue
my_ttest2 <- function(data, variable, by, ...) {
t.test(data[[variable]] ~ as.factor(data[[by]])) %>%
broom::tidy() %>%
mutate(
stat = str_glue("t={style_sigfig(statistic)}, {style_pvalue(p.value, prepend_p = TRUE)}")
) %>%
pull(stat)
}
add_stat_ex2 <-
trial %>%
select(trt, age, marker) %>%
tbl_summary(by = trt, missing = "no") %>%
add_stat(fns = everything() ~ my_ttest2) %>%
modify_header(add_stat_1 ~ "**Treatment Comparison**")
# Example 3 ----------------------------------
# return test statistic and p-value is separate columns
my_ttest3 <- function(data, variable, by, ...) {
t.test(data[[variable]] ~ as.factor(data[[by]])) %>%
broom::tidy() %>%
select(statistic, p.value)
}
add_stat_ex3 <-
trial %>%
select(trt, age, marker) %>%
tbl_summary(by = trt, missing = "no") %>%
add_stat(fns = everything() ~ my_ttest3) %>%
modify_header(
list(
statistic ~ "**t-statistic**",
p.value ~ "**p-value**"
)
) %>%
modify_fmt_fun(
list(
statistic ~ style_sigfig,
p.value ~ style_pvalue
)
)
# }
Run the code above in your browser using DataLab