Adds one or more columns of statistics computed by functions you supply,
one call per variable, to a table created with tbl_summary(). Each
function returns a single value, or a vector or data frame with one
element or row per row the statistic belongs on (see location). A
single value goes into a column named add_stat_1, add_stat_2, and so
on; the columns of a data frame keep their names, and a numeric column
named p.value or q.value is formatted as a p-value.
Arguments
- x
(
tbl_summary)
A table created withtbl_summary().- fns
(formula-list)
The function to run for each variable, e.g.list(all_continuous() ~ my_stat). Each function is called asfn(data = , variable = , by = , tbl = ): the data frame of the table, the variable name, thebyvariable name (orNULL) and the table itself. A function that accepts...receives all of them; otherwise only the arguments it declares are passed.- location
(formula-list)
The rows the statistic is placed on, per variable:"label"(the default),"level"or"missing". With"level", the function returns one value per level.
Value
A table of class c("tbl_summary", "ltsummary") with the new
columns shown; numeric columns are formatted with
label_style_sigfig(digits = 3).
See also
modify_header() to name the new column, modify_fmt_fun() to
change its formatting.
Other add statistics:
add_ci(),
add_difference(),
add_difference_row(),
add_n(),
add_overall(),
add_p(),
add_p_continuous,
add_q(),
add_stat_label(),
tests
Examples
# Example 1 ----------------------------------
# a p-value from a Kruskal-Wallis test, one row per variable
my_kruskal <- function(data, variable, by, ...) {
kruskal.test(data[[variable]] ~ as.factor(data[[by]]))$p.value
}
trial |>
tbl_summary(by = trt, include = c(age, marker), missing = "no") |>
add_stat(fns = everything() ~ my_kruskal) |>
modify_header(add_stat_1 = "**p-value**")
# Example 2 ----------------------------------
# a data frame of statistics, placed on the level rows
level_counts <- function(data, variable, by, ...) {
counts <- table(data[[variable]])
data.frame(n_level = as.vector(counts), p_level = as.vector(prop.table(counts)))
}
trial |>
tbl_summary(by = trt, include = grade, missing = "no") |>
add_stat(fns = grade ~ level_counts, location = grade ~ "level") |>
modify_header(n_level = "**N**", p_level = "**Fraction**")