f_t_test: Perform multiple t-tests with optional data transformation,...

View source: R/fttest.R

f_t_testR Documentation

Perform multiple t-tests with optional data transformation, inspection and visualization.

Description

Performs One-sample, Two-sample (Independent), or Paired t-tests on a given dataset with options for (Box-Cox/BestNormalize) transformations, normality tests, and visualization. Several response parameters can be analysed in sequence (formula interface). Additionally, a vector interface similar to stats::t.test() is supported.

Usage

f_t_test(x, ...)

## S3 method for class 'formula'
f_t_test(
  formula,
  data = NULL,
  paired = NULL,
  paired_by = NULL,
  var.equal = NULL,
  conf.level = NULL,
  mu = 0,
  alternative = "two.sided",
  norm_plots = TRUE,
  transformation = TRUE,
  force_transformation = NULL,
  alpha = 0.05,
  intro_text = TRUE,
  close_generated_files = FALSE,
  open_generated_files = interactive(),
  output_type = "default",
  save_as = NULL,
  save_in_wdir = FALSE,
  ...
)

## Default S3 method:
f_t_test(
  x,
  y = NULL,
  paired = FALSE,
  var.equal = NULL,
  conf.level = NULL,
  mu = 0,
  alternative = "two.sided",
  norm_plots = TRUE,
  transformation = TRUE,
  force_transformation = NULL,
  alpha = 0.05,
  intro_text = TRUE,
  close_generated_files = FALSE,
  open_generated_files = interactive(),
  output_type = "default",
  save_as = NULL,
  save_in_wdir = FALSE,
  ...
)

Arguments

x

Numeric vector of data values (one-sample or first group for two-sample), or a formula of the form response ~ group or response ~ 1.

...

For the formula method: additional arguments forwarded to the row-filtering step. The arguments subset and na.action are honored: when supplied, they are spliced (still unevaluated) into a model.frame call built once before the per-response loop, so the subset expression is evaluated in the data's column scope (e.g. subset = cyl == 6 works). All responses in a multi-response call (y1 + y2 ~ group) are then tested on the identical row set. For the default (vector) method, ... is currently unused.

formula

A formula specifying the model (alternative to using x/y).

  • Two-sample (Independent/Paired): response ~ group (where group has exactly 2 levels).

  • One-sample: response ~ 1 or response ~ NULL.

More response variables can be added using + (e.g., y1 + y2 ~ group).

data

A data frame containing the variables when using the formula interface.

paired

Logical or NULL. If TRUE, performs a paired t-test. If FALSE, an independent (or one-sample) test. If NULL (default) and paired_by is supplied, paired is automatically set to TRUE (with a message), since paired_by has no purpose outside a paired test. An explicit paired = FALSE is never overridden. Note: For the formula interface, supply paired_by to identify matched pairs by subject id. If paired_by is omitted, the data must be sorted so that all observations of group 1 appear before group 2 (AABB order) and the within-group order must be identical across groups, because the pairing is then purely positional and fragile. A warning is issued if the data appear interleaved (not in AABB order); a within-group reordering that preserves AABB blocks cannot be detected automatically, so supply paired_by whenever a subject id is available. For the vector interface, x and y must have the same length (pairing is positional by construction).

paired_by

Character string. For the formula interface with paired = TRUE, the name of a column in data that identifies matched pairs (subject id). When supplied, observations are matched by this id rather than by row position, so the data no longer needs to be in AABB order. Each id must appear exactly once per group, and the two groups must contain the same set of ids (after subset and NA removal). Ignored for one-sample and two-sample independent tests, and for the vector interface. Default NULL.

var.equal

Logical or NULL. If TRUE, forces Student's t-test (equal variances). If FALSE or NULL (default), Welch's t-test is used. Bartlett's and Levene's tests are always reported as diagnostics but do not affect this choice. See Delacre, Lakens & Leys (2017).

conf.level

Numeric. Confidence level. Default is 1 - alpha. If conf.level is specified, alpha is set to 1 - conf.level.

mu

Numeric. The true value to test against: the mean (one-sample), the mean of differences (paired), or the difference in means (two-sample). Default is 0. For transformed analyses, mu is forward-transformed for one-sample and paired tests. For two-sample tests with mu != 0 a warning is issued.

alternative

Character string. "two.sided" (default), "greater", or "less".

norm_plots

Logical. If TRUE, diagnostic plots are included in the output. Default is TRUE.

transformation

Logical or character string. If TRUE or "boxcox", applies f_boxcox() when Shapiro-Wilk indicates non-normality. If "bestnormalize", applies f_bestNormalize(). If FALSE or "none", no transformation is applied. Note: For paired tests, bestNormalize (Yeo-Johnson) is always used on the differences, since Box-Cox requires strictly positive values. Default is TRUE.

force_transformation

Character vector. Names of variables to transform regardless of normality results.

alpha

Numeric. Significance level. Default is 0.05.

intro_text

Logical. If TRUE, includes explanation of t-test assumptions. Default is TRUE.

close_generated_files

Logical. Closes open Excel/Word files before writing. Default FALSE. Windows only.

open_generated_files

Logical. Whether to open the generated output files after creation. Defaults to TRUE in an interactive R session and FALSE otherwise (e.g. in scripts or automated pipelines). Set to TRUE or FALSE to override this behaviour explicitly.

output_type

Character string specifying the output format. Default is "default".

  • "default": Returns the object and lets R decide whether to print; auto-prints if unassigned, silent if assigned to a variable. Use print(result) or plot(result) to display the returned object.

  • "console": Forces immediate printing to the console regardless of object assignment.

  • "pdf", "word", "excel": Saves results to a file of the corresponding format. See save_as, save_in_wdir, and open_generated_files for file path and opening behavior.

  • "rmd": Stores the raw markdown string inside the returned object for use in R Markdown documents.

save_as

Character. Specific path/filename for output.

save_in_wdir

Logical. Save in working directory. Default FALSE.

y

Optional numeric vector (second group) for two-sample tests if using the vector interface. Ignored when a formula is supplied.

Value

An object of class 'f_t_test', a named list with one element per response variable. Each element contains the t-test result, normality test results, variance diagnostic results, transformation object (if applied), back-transformed confidence interval (if applicable), and a publication-ready main effect plot as a ggplot2 object (main_effect_plot). The plot shows the estimated parameter with its confidence interval against the raw data: group means with their mean confidence intervals (two-sample), the sample mean with a reference line at mu (one-sample), or the mean of the per-pair differences with a reference line at mu (paired). When the response was transformed the estimate and interval are back-transformed to the original scale and labelled as a median.

Author(s)

Sander H. van Delden plantmind@proton.me

References

Delacre, M., Lakens, D., & Leys, C. (2017). Why psychologists should by default use Welch's t-test instead of Student's t-test. International Review of Social Psychology, 30(1), 92-101. \Sexpr[results=rd]{tools:::Rd_expr_doi("10.5334/irsp.82")}

Examples


# 1. Two-sample independent Welch's t-test (default)
f_t_test(mpg ~ am, data = mtcars, output_type = "console", norm_plots = FALSE)

# 2. Multiple response variables in one call
f_t_test(mpg + hp ~ am, data = mtcars, output_type = "console", norm_plots = FALSE)

# 3. One-sample t-test: test if mean mpg equals 20
f_t_test(mpg ~ 1, data = mtcars, mu = 20,
         output_type = "console", norm_plots = FALSE)

# 4. Paired t-test with explicit subject id (recommended)
f_t_test(extra ~ group, data = sleep, paired = TRUE, paired_by = "ID",
         output_type = "console", norm_plots = FALSE)

# 4b. Paired t-test without paired_by (warns; pairing is positional and
# only safe when data is in AABB order with matching within-group order)
f_t_test(extra ~ group, data = sleep, paired = TRUE,
         output_type = "console", norm_plots = FALSE)

# 5. Vector interface: two-sample independent
group_auto   <- mtcars$mpg[mtcars$am == 0]
group_manual <- mtcars$mpg[mtcars$am == 1]
f_t_test(group_auto, group_manual, output_type = "console", norm_plots = FALSE)

# 6. Vector interface: one-sample
f_t_test(mtcars$mpg, mu = 20, output_type = "console", norm_plots = FALSE)

# 7. Force Student's t-test (equal variances assumed)
f_t_test(mpg ~ am, data = mtcars, var.equal = TRUE,
         output_type = "console", norm_plots = FALSE)

# 8. One-sided test
f_t_test(mpg ~ am, data = mtcars, alternative = "greater",
         output_type = "console", norm_plots = FALSE)

# 9. Custom significance level (alpha = 0.01 is equivalent to conf.level = 0.99)
f_t_test(mpg ~ am, data = mtcars, alpha = 0.01,
         output_type = "console", norm_plots = FALSE)

# 10. Box-Cox transformation with back-transformed CI
# The back-transformed CI estimates the MEDIAN, not the arithmetic mean.
result <- f_t_test(hp ~ am, data = mtcars, transformation = TRUE,
                   output_type = "console", norm_plots = FALSE)
result[["hp"]]$ci_backtransformed

# 11. One-sample with non-zero mu and back-transformation
f_t_test(hp ~ 1, data = mtcars, mu = 100, transformation = TRUE,
         output_type = "console", norm_plots = FALSE)

# 12. BestNormalize transformation (set seed for reproducibility)
set.seed(123)
f_t_test(hp ~ am, data = mtcars, transformation = "bestnormalize",
         output_type = "console", norm_plots = FALSE)

# 13. Force transformation regardless of normality
f_t_test(mpg + hp ~ am, data = mtcars, force_transformation = "mpg",
         output_type = "console", norm_plots = FALSE)

# 14. Suppress transformation (diagnostic mode)
f_t_test(hp ~ am, data = mtcars, transformation = FALSE,
         output_type = "console", norm_plots = FALSE)

# 15. Access return object fields directly
result <- f_t_test(mpg + hp ~ am, data = mtcars,
                   output_type = "default", norm_plots = FALSE, intro_text = FALSE)
result[["mpg"]]$t_test          # standard htest object
result[["hp"]]$shapiro_res      # Shapiro-Wilk result
result[["hp"]]$homog_p_bartlett # Bartlett p-value (diagnostic only)
result[["hp"]]$homog_p_levene   # Levene p-value (diagnostic only)
result[["hp"]]$ci_backtransformed # back-transformed CI if transformed

# 16. Retrieve and customise the stored main effect plot (ggplot object)
result[["mpg"]]$main_effect_plot
# e.g. add a custom title:
# result[["mpg"]]$main_effect_plot + ggplot2::ggtitle("My title")


rfriend documentation built on July 7, 2026, 1:06 a.m.