Experimental lifecycle The function allows a user to add a new column with a custom, user-defined statistic.

add_stat(
  x,
  fns,
  fmt_fun = NULL,
  header = "**Statistic**",
  footnote = NULL,
  new_col_name = NULL
)

Arguments

x

tbl_summary object

fns

list of formulas indicating the functions that create the statistic

fmt_fun

for numeric statistics, fmt_fun= is the styling/formatting function. Default is NULL

header

Column header of new column. Default is "**Statistic**"

footnote

Footnote associated with new column. Default is no footnote (i.e. NULL)

new_col_name

name of new column to be created in .$table_body. Default is "add_stat_1", unless that column exists then it is "add_stat_2", etc.

Details

The custom functions passed in fns= are required to follow a specified format. Each of these function will execute on a single variable from tbl_summary().

  1. Each function must return a single scalar or character value of length one.

  2. Each function may take the following arguments: foo(data, variable, by, tbl)

  • data= is the input data frame passed to tbl_summary()

  • variable= is a string indicating the variable to perform the calculation on

  • by= is a string indicating the by variable from tbl_summary=, if present

  • tbl= the original tbl_summary() object is also available to utilize

The user-defined does not need to utilize each of these inputs. It's encouraged the user-defined function accept ... as each of the arguments will be passed to the function, even if not all inputs are utilized by the user's function, e.g. foo(data, variable, by, ...)

Example Output

Example 1

Example 2

Examples

# Example 1 ---------------------------------- # this example replicates `add_p()` # 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_p(test = everything() ~ t.test) %>% # replicating result of `add_p()` with `add_stat()` add_stat( fns = everything() ~ my_ttest, # all variables compared with with t-test fmt_fun = style_pvalue, # format result with style_pvalue() header = "**My p-value**" # new column header ) # Example 2 ---------------------------------- # fn returns t-test test statistic and pvalue my_ttest2 <- function(data, variable, by, ...) { tt <- t.test(data[[variable]] ~ as.factor(data[[by]])) # returning test statistic and pvalue stringr::str_glue( "t={style_sigfig(tt$statistic)}, {style_pvalue(tt$p.value, prepend_p = TRUE)}" ) } add_stat_ex2 <- trial %>% select(trt, age, marker) %>% tbl_summary(by = trt, missing = "no") %>% add_stat( fns = everything() ~ my_ttest2, # all variables will be compared by t-test fmt_fun = NULL, # fn returns and chr, so no formatting function needed header = "**Treatment Comparison**", # column header footnote = "T-test statistic and p-value" # footnote ) # Example 1 ----------------------------------