statsExpressions

repository·main·Indexed 43 days ago

https://github.com/indrajeetpatil/statsexpressions

An R package providing a unified, pipe-friendly interface for statistical analyses on tidy dataframes. It supports parametric, non-parametric, robust, and Bayesian approaches for tests including one-sample and two-sample t-tests, one-way ANOVA, correlation analysis, contingency tables, and meta-analysis. The package returns results as tidy dataframes and generates pre-formatted statistical expressions optimized for use in ggplot2 visualizations.

Tokens
5.1K
Snippets
15
Records
24
Agent score
6%

What's inside statsExpressions

  1. Overview of statsExpressions functionality

    main

    The {statsExpressions} package provides a consistent, pipe-friendly syntax for performing statistical analysis on tidy dataframes and generates pre-formatted statistical expressions for use in plots. It acts as a unified backend for many statistical packages, handling different data formats (wide vs. long) and input requirements internally.

    Available Analyses

    TestFunction
    one-sample t-testone_sample_test()
    two-sample t-testtwo_sample_test()
    one-way ANOVAoneway_anova()
    correlation analysiscorr_test()
    contingency table analysiscontingency_table()
    meta-analysismeta_analysis()
    pairwise comparisonspairwise_comparisons()
    pairwise contingency tablepairwise_contingency_table()

    Supported Statistical Approaches

    DescriptionParametricNon-parametricRobustBayesian
    Between group/condition comparisons✅✅✅✅
    Within group/condition comparisons✅✅✅✅
    Distribution of a numeric variable✅✅✅✅
    Correlation between two variables✅✅✅✅
    Association between categorical variables✅✅❌✅
    Equal proportions for categorical variable levels✅✅❌✅
    Random-effects meta-analysis✅❌✅✅
  2. Integration with `{ggstatsplot}`

    main

    The functions in statsExpressions were originally designed to display statistical results on {ggplot2} plots implemented in the {ggstatsplot} package. When used within {ggstatsplot}, the statistical expressions (results) are typically displayed in the plot's subtitle.

    For detailed documentation on using these results in visualizations, visit the {ggstatsplot} website: https://www.indrapatil.com/ggstatsplot/

  3. Use statistical expressions for plotting

    main
    Every result dataframe returned by {statsExpressions} includes an expression column. This column contains a pre-formatted text string (a list) that follows standard statistical reporting guidelines for both Bayesian and Frequentist frameworks. This is designed to be used directly in plot labels (e.g., as a subtitle) to display test results alongside visualizations.
  4. Handle statistical expressions in plots

    main

    All statistical functions in statsExpressions return a data frame containing an expression column. This column is a list of R expressions used to create formatted statistical subtitles in plots (e.g., using ggplot2).

    Depending on your needs, you can use the expression column in two ways:

    1. Single result: If you only have one result to display, you can extract the first element directly without parsing: results_data$expression[[1]].
    2. Multiple results: If you are displaying multiple expressions (e.g., in a grouped data frame), you must parse them using parse(text = results_data$expression) to ensure they render correctly in ggplot2 labels.

    If you want to customize the details (e.g., only showing the $p$-value and statistic), you can extract the list and manually construct a new expression using ggplot2::expr() or paste() functions.

    # Example: Using parsed expressions for multiple results
    results_data <- oneway_anova(iris, Species, Sepal.Length, type = "robust")
    
    ggplot(iris, aes(x = Sepal.Length, y = Species)) +
      geom_density_ridges() +
      labs(
        subtitle = parse(text = results_data$expression)
      )
  5. Install the statsExpressions package

    main

    You can install {statsExpressions} from CRAN for the release version, or use pak to install the development version.

    On Linux, you may need to install additional system dependencies. You can check for these using pak::pkg_sysreqs("statsExpressions").

    # Release version
    install.packages("statsExpressions")
    
    # Development version
    pak::pak("IndrajeetPatil/statsExpressions")
    
    # Check Linux system dependencies
    pak::pkg_sysreqs("statsExpressions")
  6. Use statistical expressions in ggplot2 plots

    main

    Every statistical analysis output includes an expression column. This column contains a pre-formatted, in-text statistical result designed for reporting (e.g., including test statistics, df, and p-values).

    Important: When using these expressions in a geometric layer (like geom_label), you must set parse = TRUE because the expressions need to be parsed by ggplot2.

    Example: Displaying centrality measures (like the mean) with labels.

    library(ggplot2)
    
    # displaying mean for each level of `cyl`
    centrality_description(mtcars, cyl, wt) |>
      ggplot(aes(cyl, wt)) +
      geom_point() +
      geom_label(aes(label = expression), parse = TRUE)
    # displaying mean for each level of `cyl`
    centrality_description(mtcars, cyl, wt) |
      ggplot(aes(cyl, wt)) +
      geom_point() +
      geom_label(aes(label = expression), parse = TRUE)
  7. Perform statistical analysis and get tidy dataframes

    main

    Statistical functions in {statsExpressions} return tidy dataframes containing results like statistics, p-values, effect sizes, and confidence intervals. You can easily switch between statistical approaches (e.g., from nonparametric to robust) by changing the type argument.

    Example: Running a one-way ANOVA using a pipe.

    mtcars |> oneway_anova(cyl, wt, type = "nonparametric")
    mtcars |> oneway_anova(cyl, wt, type = "robust")
    # Example: switching statistical approaches
    mtcars |> oneway_anova(cyl, wt, type = "nonparametric")
    
    mtcars |> oneway_anova(cyl, wt, type = "robust")
  8. Display statistical results in a ggplot2 plot

    main

    To display statistical results in a plot, capture the output of a {statsExpressions} function and use the expression column in your labs() call. This example uses ggridges to create a ridgeplot with the test results in the subtitle.

    # needed libraries
    library(statsExpressions)
    library(ggplot2)
    library(ggridges)
    library(palmerpenguins) # `penguins` dataset is from this package
    
    # creating a dataframe
    res <- oneway_anova(penguins, species, body_mass_g, type = "nonparametric")
    
    # create a ridgeplot using `ggridges` package
    ggplot(penguins, aes(x = body_mass_g, y = species)) +
      geom_density_ridges(
        jittered_points = TRUE,
        quantile_lines = TRUE,
        scale = 0.9,
        vline_size = 1,
        vline_color = "red",
        position = position_raincloud(adjust_vlines = TRUE)
      ) + # use 'expression' column to display results in the subtitle
      labs(
        x = "Penguin species",
        y = "Body mass (in grams)",
        title = "Kruskal-Wallis Rank Sum Test",
        subtitle = res$expression[[1]]
      )
  9. Run grouped statistical operations with dplyr

    main

    Because {statsExpressions} functions are designed for tidy data, they are compatible with dplyr verbs. You can use group_modify() to run a statistical test for every level of a grouping variable.

    library(dplyr)
    
    # Running a one-sample test for all levels of grouping variable `cyl`
    mtcars |>
      group_by(cyl) |> 
      group_modify(~ one_sample_test(.x, wt, test.value = 3), .keep = TRUE) |> 
      ungroup()
    # for reproducibility
    set.seed(123)
    library(dplyr)
    
    # grouped operation
    # running one-sample test for all levels of grouping variable `cyl`
    mtcars |
      group_by(cyl) |
      group_modify(~ one_sample_test(.x, wt, test.value = 3), .keep = TRUE) |
      ungroup()
  10. Run statistical tests across groups using dplyr

    main

    Because {statsExpressions} functions are pipe-friendly and return tidy dataframes, they integrate seamlessly with dplyr. You can use group_by() and group_modify() to run the same statistical test (e.g., contingency_table) across all levels of a grouping variable.

    # running one-sample proportion test for all levels of `cyl`
    mtcars %>%
      group_by(cyl) %>%
      group_modify(~ contingency_table(.x, am), .keep = TRUE) %>%
      ungroup()
  11. Perform a one-way ANOVA with different statistical types

    main

    Use oneway_anova() to perform ANOVA. You can easily switch between nonparametric and robust approaches by modifying the type argument. The function requires a tidy dataframe, a grouping variable, and a continuous variable.

    # Non-parametric ANOVA
    mtcars %>% oneway_anova(cyl, wt, type = "nonparametric")
    
    # Robust ANOVA
    mtcars %>% oneway_anova(cyl, wt, type = "robust")
  12. Perform correlation tests with `corr_test`

    main

    The corr_test function handles both hypothesis testing and effect size estimation for correlations.

    Supported Methods

    • Parametric: Pearson’s correlation coefficient (correlation::correlation())
    • Non-parametric: Spearman’s rank correlation coefficient (correlation::correlation())
    • Robust: Winsorized Pearson’s correlation coefficient (correlation::correlation())
    • Bayesian: Bayesian Pearson’s correlation coefficient (correlation::correlation())

    All methods provide Confidence Intervals (CI).