| rstatix-programming | R Documentation |
How to use rstatix functions programmatically — i.e. when the variable
names are held in character strings or passed into your own wrapper functions,
as is common in package development, loops, and Shiny apps.
rstatix has two kinds of interfaces, and each supports a standard way of
"programming over variables":
Selection interface (functions that select columns through
... or vars=, e.g. cor_test(),
get_summary_stats(), cor_mat(),
freq_table()). These support full tidy-evaluation: bare names,
the injection operators !!/!!!, the embracing operator
{{ }} inside your own functions, a character vector via
vars=, and tidyselect helpers such as all_of()/any_of().
Formula interface (tests that take a formula, e.g.
t_test(), wilcox_test(), kruskal_test(),
anova_test(), friedman_test()). A formula is an
ordinary R object, so build it from strings with reformulate()
or stats::as.formula(paste(...)) and pass it in.
Injecting a string directly into a raw formula (e.g. t_test(df, y ~ {{var}}))
is not supported: a formula is captured as a syntax tree, not a quosure,
so the embracing/injection operators do not apply there. Build the formula
instead with reformulate(rhs, lhs) — see the examples.
In examples below, helpers that rstatix does not re-export are namespaced
(rlang::sym, dplyr::all_of, dplyr::across); attach
rlang/dplyr and you can drop the prefixes.
cor_test(), get_summary_stats(),
t_test().
# Selection interface -----------------------------------------------------
# A variable name held in a string, injected with !!
x <- "mpg"; y <- "wt"
mtcars %>% cor_test(!!rlang::sym(x), !!rlang::sym(y))
# Several names at once, spliced with !!!
vars <- c("mpg", "disp", "hp")
mtcars %>% cor_test(!!!rlang::syms(vars))
# A character vector via `vars =` (no rlang needed)
mtcars %>% cor_test(vars = c("mpg", "disp"))
# tidyselect helpers
iris %>% get_summary_stats(dplyr::all_of(c("Sepal.Length", "Sepal.Width")))
# Your own wrapper function: embrace the argument with {{ }}
my_summary <- function(data, var) {
data %>% get_summary_stats({{ var }}, type = "mean_sd")
}
my_summary(iris, Sepal.Length)
# Formula interface -------------------------------------------------------
# Build the formula from strings with reformulate(rhs, lhs)
outcome <- "len"; group <- "supp"
ToothGrowth %>% t_test(reformulate(group, outcome))
# The same inside a wrapper function
my_test <- function(data, outcome, group) {
data %>% t_test(reformulate(group, outcome))
}
my_test(ToothGrowth, "len", "supp")
# Programmatic grouping + a built formula (a common end-to-end pattern)
gv <- "supp"
ToothGrowth %>%
group_by(dplyr::across(dplyr::all_of(gv))) %>%
t_test(reformulate("dose", "len"))
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.