rstatix

repository·master·Indexed 18 days ago

https://github.com/kassambara/rstatix

A pipe-friendly, tidyverse-compatible framework for performing common statistical tests in R. It transforms statistical outputs into tidy data frames for seamless integration with ggplot2. Key capabilities include t-tests, ANOVA (independent, repeated measures, and mixed), correlation analysis with matrix manipulation tools, descriptive statistics via get_summary_stats(), and assumption checking for normality and homogeneity of variance.

Tokens
2.4K
Snippets
11
Records
13
Agent score
65%

What's inside rstatix

  1. Overview of rstatix capabilities

    master

    rstatix is a pipe-friendly framework for performing statistical tests in R, designed to be coherent with the tidyverse philosophy.

    Key features include:

    • Tidy Outputs: Every test result is automatically transformed into a tidy data frame, making it easy to use with ggplot2, dplyr, and other tidyverse tools.
    • Comprehensive Tests: Supports t-tests, Wilcoxon, ANOVA (including repeated measures and mixed designs), Kruskal-Wallis, correlation, and proportion tests.
    • Assumption Checking: Includes functions for normality (Shapiro-Wilk), homogeneity of variance (Levene, Fligner-Killeen), and outlier detection.
    • Effect Size: Computes metrics like Cohen's d, eta squared, Cramer's V, and more.
    • Post-hoc Analysis: Provides automated decision trees for post-hoc tests (e.g., Tukey HSD, Games-Howell, Dunn's test).
    • Correlation Tools: Advanced tools for computing, reshaping, subsetting, and visualizing correlation matrices.
  2. Install and load rstatix

    master

    You can install rstatix from CRAN or the latest developmental version from GitHub. For easy data visualization, it is recommended to load ggpubr alongside it.

    To install from CRAN:

    install.packages("rstatix")

    To install the latest developmental version from GitHub:

    if(!require(devtools)) install.packages("devtools")
    devtools::install_github("kassambara/rstatix")

    To load the packages in your R session:

    library(rstatix)
    library(ggpubr)
    library(rstatix)
    library(ggpubr)
  3. Manipulate and visualize correlation matrices

    master

    Once a correlation matrix is created using cor_mat(), you can reshape, subset, and visualize it.

    Reshaping:

    • cor_gather(): Melt a matrix into long format.
    • cor_spread(): Spread long format back to wide format.
    • cor_reorder(): Reorder matrix using hierarchical clustering.

    Subsetting:

    • pull_lower_triangle(), pull_upper_triangle(): Extract triangular parts.
    • replace_lower_triangle(), replace_upper_triangle(): Replace triangular parts.
    • cor_select(): Subset by variable names.

    Visualization:

    • cor_plot(): Visualize using base R plots.
    • cor_as_symbols(): Replace coefficients with symbols (e.g., *, +, .).
    • cor_mark_significant(): Add significance levels to the matrix.

    Example workflow:

    cor.mat %>%
      cor_reorder() %>%
      pull_lower_triangle() %>% 
      cor_plot()
    cor.mat %>%
      cor_reorder() %>%
      pull_lower_triangle() %>% 
      cor_plot()
  4. Add statistical significance to plots

    master

    To visualize statistical results on plots (typically ggplot2 objects), use stat_pvalue_manual() from the ggpubr package in conjunction with rstatix test results. This allows you to pass p-values, significance levels, or custom labels directly onto the plot.

    # Example: Adding p-values to a boxplot
    stat.test <- df %>% t_test(len ~ supp)
    
    p <- ggboxplot(df, x = "supp", y = "len")
    p + stat_pvalue_manual(stat.test, label = "p", y.position = 35)
    
    # Example: Customizing labels with glue
    p + stat_pvalue_manual(stat.test, label = "T-test, p = {p}", y.position = 36)
  5. Add statistical significance to ggplots

    master

    You can visualize test results on plots using stat_pvalue_manual() from the ggpubr integration.

    Manual p-value placement:

    p <- ggboxplot(df, x = "supp", y = "len", color = "supp", palette = "jco", ylim = c(0,40))
    stat.test <- df %>% t_test(len ~ supp, paired = FALSE)
    p + stat_pvalue_manual(stat.test, label = "p", y.position = 35)

    Customizing labels with glue:

    p + stat_pvalue_manual(stat.test, label = "T-test, p = {p}", y.position = 36)

    Using significance symbols:

    p + stat_pvalue_manual(stat.test, label = "p.adj.signif", y.position = 35)

    Removing brackets:

    p + stat_pvalue_manual(stat.test, label = "p.adj.signif", y.position = 35, remove.bracket = TRUE)
    p + stat_pvalue_manual(stat.test, label = "p", y.position = 35)
  6. Perform ANOVA tests with anova_test()

    master

    The anova_test() function is a wrapper around car::Anova() used to perform various ANOVA tests, including independent measures, repeated measures, and mixed ANOVA. It returns a list containing the ANOVA table and assumption checks (like Mauchly's test for sphericity).

    One-way ANOVA:

    df %>% anova_test(len ~ dose)

    Two-way ANOVA:

    df %>% anova_test(len ~ supp*dose)

    Two-way repeated measures ANOVA:

    df %>% anova_test(dv = len, wid = id, within = c(supp, dose))

    Using a model object:

    .my.model <- lm(yield ~ block + N*P*K, npk)
    anova_test(.my.model)
    df %>% anova_test(len ~ dose)
  7. Analyze correlations with cor_test() and cor_mat()

    master

    The package provides a suite of tools for correlation analysis.

    Correlation test between two variables:

    mydata %>% cor_test(wt, mpg, method = "pearson")

    Correlation of one variable against all others:

    mydata %>% cor_test(mpg, method = "pearson")

    Pairwise correlation test between all variables:

    mydata %>% cor_test(method = "pearson")

    Compute a correlation matrix:

    cor.mat <- mydata %>% cor_mat()

    Extract p-values from a correlation matrix:

    cor.mat %>% cor_get_pval()
    mydata %>% cor_test(wt, mpg, method = "pearson")
  8. Perform t-tests with t_test()

    master

    The t_test() function performs one-sample, two-sample, and pairwise t-tests. It is pipe-friendly and returns results as a tidy data frame.

    One-sample test (comparing a sample mean to a known mu):

    # Compare len to mu = 0
    df %>% t_test(len ~ 1, mu = 0)

    Two-sample independent test:

    df %>% t_test(len ~ supp, paired = FALSE)

    Paired samples test:

    df %>% t_test(len ~ supp, paired = TRUE)

    Multiple pairwise comparisons (when grouping variable has >2 categories):

    df %>% t_test(len ~ dose)

    Comparisons against a reference group:

    df %>% t_test(len ~ dose, ref.group = "0.5")

    Comparisons against the base-mean (all groups):

    df %>% t_test(len ~ dose, ref.group = "all")
    df %>% t_test(len ~ supp, paired = FALSE)
  9. Compute descriptive statistics with get_summary_stats()

    master

    The get_summary_stats() function computes summary statistics for one or multiple numeric variables. It supports grouped data and different types of summaries (e.g., type = "common" or type = "mean_sd").

    Example for common statistics across variables:

    iris %>% 
      get_summary_stats(Sepal.Length, Sepal.Width, type = "common")

    Example for grouped data:

    iris %>%
      group_by(Species) %>% 
      get_summary_stats(Sepal.Length, type = "mean_sd")
    iris %>% 
      get_summary_stats(Sepal.Length, Sepal.Width, type = "common")
  10. Adjust Cramer's V calculation in rstatix

    master

    In version 1.1.0, cramer_v() changed its default behavior regarding Yates' continuity correction. The correct argument now defaults to FALSE. This change ensures the function returns the standard sqrt(chi2 / (N * (k - 1))) for 2x2 tables, matching the behavior of DescTools::CramerV() and effectsize::cramers_v(adjust = FALSE).

    If you require the previous behavior (applying Yates' correction), you must explicitly set correct = TRUE.

    # Standard behavior (new default)
    cramer_v(data, correct = FALSE)
    
    # Previous behavior (manual override)
    cramer_v(data, correct = TRUE)
  11. Corrected Eta-squared calculations for Anova tables

    master

    As of version 1.1.0, eta_squared() and partial_eta_squared() have been updated to correctly handle tables generated by car::Anova(type = 3). The functions now exclude the (Intercept) row from calculations. Previously, including the intercept inflated the denominator and produced incorrect values.

    Note that inputs from standard aov or stats::anova() do not carry an intercept row and remain unaffected by this change.

  12. Perform correlation tests with cor_test()

    master

    The cor_test() function performs correlation tests between variables using Pearson, Spearman, or Kendall methods. It can be used for a single pair, one variable against all others, or pairwise correlations across all variables in a data frame.

    # Correlation between two specific variables
    mydata %>% cor_test(wt, mpg, method = "pearson")
    
    # Correlation of one variable against all others
    mydata %>% cor_test(mpg, method = "pearson")
    
    # Pairwise correlation test between all variables
    mydata %>% cor_test(method = "pearson")