Here is one solution using a custom function and the incredibly versatile gtsummary::add_stat()
function:
library(gtsummary)
# Create custom function using gtsummary syntax to be used in add_stat().
# `variable` will represent all the columns in your dataframe passed to `tbl_summary()`.
# Hardcode the variable against which you want corr (in this case `mpg`)
fn_add_tau_and_p <- function(data, variable, ...) {
t <- cor.test(data[[variable]], data[["mpg"]], method = "kendall")
data.frame(`tau` = style_sigfig(t$estimate), `p` = style_pvalue(t$p.value))
}
# test individually
fn_add_tau_and_p(mtcars, "hp")
#> tau p
#> tau -0.74 <0.001
# Now use `add_stat()` to add your function to `tbl_summary()`
mtcars |>
select(hp, disp, wt, mpg, gear) |>
tbl_summary(
) |>
add_stat(fns = all_continuous() ~ fn_add_tau_and_p)
Note: you can also use broom::tidy()
within your custom function as an alternative, as per example 2 here.