| Title: | Miscellaneous Functions for Data Processing and Analysis |
|---|---|
| Description: | A comprehensive R package providing miscellaneous functions for data processing, statistical analysis, and visualization. Includes functions for latent profile clustering via the 'latents' package, comparison plots with statistical testing, and mosaic plot analysis for categorical variables. The package offers robust error handling, comprehensive documentation, and user-friendly interfaces for complex statistical tasks. |
| Authors: | Mohammed Saqr [aut, cre] |
| Maintainer: | Mohammed Saqr <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.9.8 |
| Built: | 2026-10-18 15:05:17 UTC |
| Source: | https://github.com/mohsaqr/Saqrmisc |
Computes row totals across specified columns and adds them as a new column.
add_total(data, cols = NULL, name = "total", na.rm = TRUE)add_total(data, cols = NULL, name = "total", na.rm = TRUE)
data |
A data frame. |
cols |
Column specification. Can be:
|
name |
Character. Name for the total column. Default: '"total"'. |
na.rm |
Logical. Remove NA values when summing? Default: 'TRUE'. |
The original data frame with an added total column.
## Not run: df <- data.frame(id = 1:3, a = c(1,2,3), b = c(4,5,6), c = c(7,8,9)) # All numeric columns add_total(df) # Specific columns by name add_total(df, cols = c("a", "b")) # Columns by index range add_total(df, cols = 2:4) # From column 2 to end add_total(df, cols = 2) # Custom name add_total(df, cols = c("a", "b"), name = "sum_ab") ## End(Not run)## Not run: df <- data.frame(id = 1:3, a = c(1,2,3), b = c(4,5,6), c = c(7,8,9)) # All numeric columns add_total(df) # Specific columns by name add_total(df, cols = c("a", "b")) # Columns by index range add_total(df, cols = 2:4) # From column 2 to end add_total(df, cols = 2) # Custom name add_total(df, cols = c("a", "b"), name = "sum_ab") ## End(Not run)
Returns one of the result's tables as a plain data.frame, so callers
never have to reach into the object. For a stratified fit (one produced with
by =), what = "strata" gives one row per stratum with its own
test, effect size and multiplicity-corrected p-value.
## S3 method for class 'mosaic_analysis' as.data.frame( x, row.names = NULL, optional = FALSE, what = c("summary", "table", "residuals", "strata", "overall"), ... )## S3 method for class 'mosaic_analysis' as.data.frame( x, row.names = NULL, optional = FALSE, what = c("summary", "table", "residuals", "strata", "overall"), ... )
x |
A |
row.names, optional
|
Ignored; present for S3 consistency. |
what |
Which table to return: |
... |
Ignored. |
A data.frame. For what = "strata", one row per stratum
with columns stratum, n, test, statistic,
df, p_value, p_adjusted, cramers_v,
effect_size and n_cells_beyond_2. For
what = "residuals" on a stratified fit, one row per stratum x cell.
set.seed(1) d <- data.frame( a = sample(c("X", "Y", "Z"), 400, replace = TRUE), b = sample(c("P", "Q"), 400, replace = TRUE), g = sample(c("g1", "g2"), 400, replace = TRUE) ) fit <- mosaic_analysis(d, "a", "b", by = "g", min_count = 5, verbose = FALSE) as.data.frame(fit, what = "strata") as.data.frame(fit, what = "overall")set.seed(1) d <- data.frame( a = sample(c("X", "Y", "Z"), 400, replace = TRUE), b = sample(c("P", "Q"), 400, replace = TRUE), g = sample(c("g1", "g2"), 400, replace = TRUE) ) fit <- mosaic_analysis(d, "a", "b", by = "g", min_count = 5, verbose = FALSE) as.data.frame(fit, what = "strata") as.data.frame(fit, what = "overall")
Automatically detects numeric and categorical variables in a data frame and generates appropriate descriptive statistics tables for each type. Numeric variables get summary statistics (mean, SD, etc.) and categorical variables get frequency tables.
auto_describe( data, group_by = NULL, numeric_stats = c("n", "mean", "sd", "median", "min", "max"), digits = 2, exclude = NULL, force_categorical = NULL, title_numeric = "Numeric Variables", title_categorical = "Categorical Variables", theme = "default", format = "gt", print = TRUE )auto_describe( data, group_by = NULL, numeric_stats = c("n", "mean", "sd", "median", "min", "max"), digits = 2, exclude = NULL, force_categorical = NULL, title_numeric = "Numeric Variables", title_categorical = "Categorical Variables", theme = "default", format = "gt", print = TRUE )
data |
A data frame to describe. |
group_by |
Optional character. Name of a grouping variable for stratified statistics. |
numeric_stats |
Character vector of statistics for numeric variables. Default: 'c("n", "mean", "sd", "median", "min", "max")'. |
digits |
Integer. Decimal places for numeric output. Default: '2'. |
exclude |
Character vector of column names to exclude. Default: 'NULL'. |
force_categorical |
Character vector of numeric column names to treat as categorical instead. Default: 'NULL'. |
title_numeric |
Title for numeric table. Default: '"Numeric Variables"'. |
title_categorical |
Title for categorical tables. Default: '"Categorical Variables"'. |
theme |
Visual theme: '"default"', '"minimal"', '"dark"', '"colorful"'. Default: '"default"'. |
format |
Output format: '"gt"' or '"data.frame"'. Default: '"gt"'. |
print |
Logical. Print tables to console? Default: TRUE. |
A list with:
numeric: Descriptive table for numeric variables (or NULL if none)
categorical: List of frequency tables for categorical variables
variable_types: Data frame showing detected variable types
## Not run: # Automatic description of all variables data <- data.frame( age = rnorm(100, 35, 10), score = rnorm(100, 75, 15), gender = sample(c("M", "F"), 100, replace = TRUE), education = sample(c("HS", "BA", "MA", "PhD"), 100, replace = TRUE) ) # Describe all variables automatically results <- auto_describe(data) # With grouping results <- auto_describe(data, group_by = "gender") # Access individual tables results$numeric results$categorical$education ## End(Not run)## Not run: # Automatic description of all variables data <- data.frame( age = rnorm(100, 35, 10), score = rnorm(100, 75, 15), gender = sample(c("M", "F"), 100, replace = TRUE), education = sample(c("HS", "BA", "MA", "PhD"), 100, replace = TRUE) ) # Describe all variables automatically results <- auto_describe(data) # With grouping results <- auto_describe(data, group_by = "gender") # Access individual tables results$numeric results$categorical$education ## End(Not run)
Creates comprehensive frequency tables for categorical variables with counts, percentages, and optional cross-tabulation. Supports chi-square tests for associations and outputs beautifully formatted gt tables.
categorical_table( data, var, by = NULL, group_by = NULL, percentages = NULL, show_n = TRUE, show_total = TRUE, show_missing = FALSE, show_header = TRUE, chi_square = TRUE, fisher = FALSE, cramers_v = TRUE, digits = 1, sort_by = "none", labels = NULL, title = NULL, subtitle = NULL, format = c("gt", "plain", "markdown", "latex", "kable"), theme = "default", combine = TRUE, interpret = FALSE, ... )categorical_table( data, var, by = NULL, group_by = NULL, percentages = NULL, show_n = TRUE, show_total = TRUE, show_missing = FALSE, show_header = TRUE, chi_square = TRUE, fisher = FALSE, cramers_v = TRUE, digits = 1, sort_by = "none", labels = NULL, title = NULL, subtitle = NULL, format = c("gt", "plain", "markdown", "latex", "kable"), theme = "default", combine = TRUE, interpret = FALSE, ... )
data |
A data frame containing the variables to summarize. |
var |
Character. Name of the primary categorical variable. |
by |
Optional character. Name of a second categorical variable for cross-tabulation. When provided, creates a contingency table. |
group_by |
Optional character. Name of a stratification variable. Creates separate tables for each level of this variable. |
percentages |
Character vector specifying which percentages to include. Options: "col" (column), "row", "total", "none". Default: c("col") for cross-tabs, c("total") for single variable. |
show_n |
Logical. Show frequency counts? Default: TRUE. |
show_total |
Logical. Include row/column totals? Default: TRUE. |
show_missing |
Logical. Include missing values as a category? Default: FALSE. |
show_header |
Logical. Show title/subtitle header? Default: TRUE. Set to FALSE to hide the table header. |
chi_square |
Logical. Compute chi-square test for cross-tabulations? Default: TRUE. |
fisher |
Logical. Also compute Fisher's exact test (for small samples)? Default: FALSE. |
cramers_v |
Logical. Compute Cramer's V effect size? Default: TRUE. |
digits |
Integer. Decimal places for percentages. Default: 1. |
sort_by |
How to sort categories: "none" (original order), "frequency" (descending), "alphabetical". Default: "none". |
labels |
Optional named character vector for category labels. |
title |
Optional character string for table title. |
subtitle |
Optional character string for table subtitle. |
format |
Character. Output format: "gt" (default, publication-ready gt table), "plain" (data frame), "markdown", "latex", or "kable". |
theme |
Character. Visual theme: "default", "minimal", "dark", or "colorful". Default: "default". |
combine |
Logical. For single variables, combine n and percent in one column? Default: TRUE. Shows as "n (pct)". |
interpret |
Logical. Pass results to AI for automatic interpretation?
Default FALSE. When TRUE, generates clean Methods and Results text using
AI. Requires API key setup (see |
... |
Additional arguments passed to |
A gt table object (default) or data frame with frequencies and percentages. For cross-tabulations with chi_square = TRUE, includes test statistics.
descriptive_table for numeric variable summaries
mosaic_analysis for mosaic plot visualization with chi-square tests
## Not run: # ============================================================ # EXAMPLE 1: Single Variable Frequency Table # ============================================================ data <- data.frame( gender = sample(c("Male", "Female", "Other"), 200, replace = TRUE, prob = c(0.45, 0.45, 0.10)), education = sample(c("High School", "Bachelor", "Master", "PhD"), 200, replace = TRUE, prob = c(0.3, 0.4, 0.2, 0.1)), country = sample(c("USA", "UK", "Germany"), 200, replace = TRUE) ) # Basic frequency table categorical_table(data, var = "gender") # With sorting by frequency categorical_table(data, var = "education", sort_by = "frequency") # ============================================================ # EXAMPLE 2: Cross-Tabulation (Two Variables) # ============================================================ categorical_table( data = data, var = "gender", by = "education", chi_square = TRUE, cramers_v = TRUE ) # ============================================================ # EXAMPLE 3: Stratified Analysis # ============================================================ categorical_table( data = data, var = "gender", by = "education", group_by = "country" ) # ============================================================ # EXAMPLE 4: Custom Labels and Formatting # ============================================================ categorical_table( data = data, var = education, labels = c( "High School" = "Secondary Education", "Bachelor" = "Bachelor's Degree", "Master" = "Master's Degree", "PhD" = "Doctorate" ), title = "Educational Attainment", subtitle = "Sample Distribution", theme = "colorful" ) # ============================================================ # EXAMPLE 5: Show Row and Column Percentages # ============================================================ categorical_table( data = data, var = gender, by = education, percentages = c("row", "col"), combine = FALSE ) ## End(Not run)## Not run: # ============================================================ # EXAMPLE 1: Single Variable Frequency Table # ============================================================ data <- data.frame( gender = sample(c("Male", "Female", "Other"), 200, replace = TRUE, prob = c(0.45, 0.45, 0.10)), education = sample(c("High School", "Bachelor", "Master", "PhD"), 200, replace = TRUE, prob = c(0.3, 0.4, 0.2, 0.1)), country = sample(c("USA", "UK", "Germany"), 200, replace = TRUE) ) # Basic frequency table categorical_table(data, var = "gender") # With sorting by frequency categorical_table(data, var = "education", sort_by = "frequency") # ============================================================ # EXAMPLE 2: Cross-Tabulation (Two Variables) # ============================================================ categorical_table( data = data, var = "gender", by = "education", chi_square = TRUE, cramers_v = TRUE ) # ============================================================ # EXAMPLE 3: Stratified Analysis # ============================================================ categorical_table( data = data, var = "gender", by = "education", group_by = "country" ) # ============================================================ # EXAMPLE 4: Custom Labels and Formatting # ============================================================ categorical_table( data = data, var = education, labels = c( "High School" = "Secondary Education", "Bachelor" = "Bachelor's Degree", "Master" = "Master's Degree", "PhD" = "Doctorate" ), title = "Educational Attainment", subtitle = "Sample Distribution", theme = "colorful" ) # ============================================================ # EXAMPLE 5: Show Row and Column Percentages # ============================================================ categorical_table( data = data, var = gender, by = education, percentages = c("row", "col"), combine = FALSE ) ## End(Not run)
Centers numeric variables by subtracting the mean. Supports group-wise centering for multilevel/nested data. Works with dplyr mutate/across.
center(data, Vars, suffix = "_c", group_by = NULL)center(data, Vars, suffix = "_c", group_by = NULL)
data |
A data frame (or vector if used in mutate). |
Vars |
Character vector of numeric variable names to center. Not needed if used in mutate. |
suffix |
Character. Suffix for new column names. Default "_c". |
group_by |
Character. Name of grouping variable for group-wise centering. Optional. |
Data frame with centered variables added, or vector if input is vector.
## Not run: # Simple mean centering df <- center(mtcars, Vars = c("mpg", "hp")) # Group-mean centering df <- center(mtcars, Vars = "mpg", group_by = "cyl") # With dplyr library(dplyr) mtcars %>% mutate(mpg_c = center_vec(mpg)) mtcars %>% mutate(across(c(mpg, hp), center_vec, .names = "{.col}_c")) # Group-wise with dplyr mtcars %>% group_by(cyl) %>% mutate(mpg_c = center_vec(mpg)) ## End(Not run)## Not run: # Simple mean centering df <- center(mtcars, Vars = c("mpg", "hp")) # Group-mean centering df <- center(mtcars, Vars = "mpg", group_by = "cyl") # With dplyr library(dplyr) mtcars %>% mutate(mpg_c = center_vec(mpg)) mtcars %>% mutate(across(c(mpg, hp), center_vec, .names = "{.col}_c")) # Group-wise with dplyr mtcars %>% group_by(cyl) %>% mutate(mpg_c = center_vec(mpg)) ## End(Not run)
Vectorized centering function for use with dplyr mutate and across. For group-wise centering, use dplyr::group_by() before mutate().
center_vec(x, na.rm = TRUE)center_vec(x, na.rm = TRUE)
x |
Numeric vector to center. |
na.rm |
Logical. Remove NA values when computing mean? Default TRUE. |
Centered numeric vector.
## Not run: library(dplyr) # Single variable mtcars %>% mutate(mpg_c = center_vec(mpg)) # Multiple variables mtcars %>% mutate(across(c(mpg, hp, wt), center_vec, .names = "{.col}_c")) # Group-wise centering mtcars %>% group_by(cyl) %>% mutate(mpg_c = center_vec(mpg)) ## End(Not run)## Not run: library(dplyr) # Single variable mtcars %>% mutate(mpg_c = center_vec(mpg)) # Multiple variables mtcars %>% mutate(across(c(mpg, hp, wt), center_vec, .names = "{.col}_c")) # Group-wise centering mtcars %>% group_by(cyl) %>% mutate(mpg_c = center_vec(mpg)) ## End(Not run)
Fits latent profile models with the latents package and keeps the
candidate with the lowest BIC. Every combination of n_profiles and
models is fitted by latents::enumerate_lpa(); a single combination is
simply a grid of one.
The result is a latents fit, so its verbs apply directly:
as.data.frame(fit) for profile means, latents::diagnostics(fit) for
classification quality, latents::get_results(fit, what) for any table.
clustering( data, vars, n_profiles = NULL, n_clusters = NULL, models = "VVI", scaling = c("standardize", "center", "minmax", "none"), n_starts = 10L, seed = NULL, na_action = c("omit", "fail"), verbose = TRUE )clustering( data, vars, n_profiles = NULL, n_clusters = NULL, models = "VVI", scaling = c("standardize", "center", "minmax", "none"), n_starts = 10L, seed = NULL, na_action = c("omit", "fail"), verbose = TRUE )
data |
A data frame. |
vars |
Character vector of numeric columns to cluster on. |
n_profiles |
Number(s) of profiles, each at least 2: one value, or a
range such as |
n_clusters |
Alias for |
models |
Covariance structure(s) as three-letter mclust codes (e.g.
|
scaling |
Transformation applied to |
n_starts |
Random starts per candidate. |
seed |
Random seed passed to latents. |
na_action |
|
verbose |
Report progress with |
An object of class c("saqr_clustering", "multilpa"): the
selected latents fit, fitted to the scaled data. Methods:
print(), summary() (one row per candidate), fitted() (the input
data with profile assignments), plot().
Raises saqrmisc_bad_input for unknown models, non-numeric or constant
vars, missing values under na_action = "fail", or fewer than 10
complete rows; saqrmisc_no_converged when no candidate converged.
Vermunt, J. K. (2003). Multilevel latent class models. Sociological Methodology, 33, 213-239.
plot_clustering(), latents::enumerate_lpa()
set.seed(1) vars <- c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width") fit <- clustering(iris, vars, n_profiles = 2:4, models = c("EEE", "VVI")) fit summary(fit) as.data.frame(fit) fitted(fit) plot(fit)set.seed(1) vars <- c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width") fit <- clustering(iris, vars, n_profiles = 2:4, models = c("EEE", "VVI")) fit summary(fit) as.data.frame(fit) fitted(fit) plot(fit)
The figures plot_clustering() can draw. Any type, any group, or
"all" can be passed as its type.
clustering_plot_types()clustering_plot_types()
A data.frame with one row per plot type and columns type,
group ("clusters", "diagnostics" or "selection") and
description.
clustering_plot_types()clustering_plot_types()
A comprehensive function for comparing groups using publication-ready visualizations and statistical tests. Creates 'ggbetweenstats' plots from the ggstatsplot package with automatic test selection based on the number of groups:
For 2 groups: t-test (parametric) or Mann-Whitney U (nonparametric). For 3+ groups: ANOVA (parametric) or Kruskal-Wallis (nonparametric) with post-hoc pairwise comparisons. Also supports Bayesian analysis, equivalence testing (TOST), and stratified analyses using repeat_category.
compare_groups( data, category, Vars = NULL, category_sep = " | ", repeat_category = NULL, compare_by = NULL, compare_mode = c("between", "within"), repeat_combine = TRUE, repeat_levels = NULL, plots = TRUE, plot_style = c("points", "boxplot", "bar", "violin", "ggstatsplot"), table = TRUE, type = "auto", bayesian = FALSE, equivalence = FALSE, equivalence_bounds = c(-0.5, 0.5), nonparametric = FALSE, p_adjust_method = "fdr", posthoc = TRUE, posthoc_method = "games-howell", posthoc_table = FALSE, posthoc_format = c("wide", "long", "both"), pairwise_display = "significant", pivot = FALSE, pivot_by = c("category", "repeat_category"), pivot_stat = c("mean", "mean_sd", "median", "n"), pivot_stars = TRUE, pivot_split_level = TRUE, min_threshold = 0.05, min_subcategory = 5, colors = NULL, verbose = TRUE, combined_table = TRUE, format = c("gt", "plain", "markdown", "latex", "kable"), show_header = TRUE, interpret = FALSE, ... )compare_groups( data, category, Vars = NULL, category_sep = " | ", repeat_category = NULL, compare_by = NULL, compare_mode = c("between", "within"), repeat_combine = TRUE, repeat_levels = NULL, plots = TRUE, plot_style = c("points", "boxplot", "bar", "violin", "ggstatsplot"), table = TRUE, type = "auto", bayesian = FALSE, equivalence = FALSE, equivalence_bounds = c(-0.5, 0.5), nonparametric = FALSE, p_adjust_method = "fdr", posthoc = TRUE, posthoc_method = "games-howell", posthoc_table = FALSE, posthoc_format = c("wide", "long", "both"), pairwise_display = "significant", pivot = FALSE, pivot_by = c("category", "repeat_category"), pivot_stat = c("mean", "mean_sd", "median", "n"), pivot_stars = TRUE, pivot_split_level = TRUE, min_threshold = 0.05, min_subcategory = 5, colors = NULL, verbose = TRUE, combined_table = TRUE, format = c("gt", "plain", "markdown", "latex", "kable"), show_header = TRUE, interpret = FALSE, ... )
data |
A data frame containing the variables to analyze. |
category |
Character. Name(s) of the grouping variable(s). Can be a single variable (e.g., "gender") or multiple variables for interaction groups (e.g., c("gender", "treatment") creates "Male | Treatment", etc.). |
Vars |
Column specification for variables to compare. Can be NULL (default, all numeric columns), a character vector of column names, a numeric vector of column indices, or a single number (from that column to end). |
category_sep |
Character. Separator for combined group labels when multiple variables are passed to category. Default: " | ". |
repeat_category |
Optional character. Name of a stratification variable. When provided, separate analyses are performed for each level (e.g., analyze gender differences separately for each country). Used with compare_mode = "between". |
compare_by |
Optional character vector. Factors to test within each category level. Used with compare_mode = "within". For example, if category = "llm" and compare_by = c("pronoun", "support"), tests whether pronoun and support have effects within each LLM dataset separately. |
compare_mode |
Character. Analysis mode: "between" (default) - compare category levels (e.g., GPT vs Mistral vs Qwen), "within" - test compare_by factors within each category level (e.g., test pronoun effect within GPT, within Mistral, within Qwen separately). |
repeat_combine |
Logical. When multiple repeat_category variables are provided with compare_mode = "between", should they be combined into one grouping (e.g., "he/him | High")? Default TRUE. |
repeat_levels |
Optional character vector. Specific levels of repeat_category to include in the analysis. If NULL (default), all levels are used. |
plots |
Logical. Generate visualizations? Default TRUE. |
plot_style |
Character. Style of plots: "points" (default, jittered with CI), "boxplot", "bar", "violin", or "ggstatsplot" (requires ggstatsplot package). |
table |
Logical. Generate summary statistics table? Default TRUE. |
type |
Character. Type of statistical test: "auto" (default), "parametric"/"p", "nonparametric"/"np", "kw" (Kruskal-Wallis), "mw" (Mann-Whitney), or "bayes"/"bf". |
bayesian |
Logical. Compute Bayesian t-tests with Bayes Factors? Default: FALSE. Requires the BayesFactor package. Can also use 'type = "bayes"'. |
equivalence |
Logical. Perform equivalence testing (TOST)? Default: FALSE. Requires the TOSTER package. |
equivalence_bounds |
Numeric vector of length 2. Equivalence bounds in Cohen's d units for TOST. Default: c(-0.5, 0.5). |
nonparametric |
Logical. Use nonparametric tests? Default: FALSE. When TRUE, uses Mann-Whitney U (2 groups) or Kruskal-Wallis (3+ groups). |
p_adjust_method |
Method for multiple comparison correction. Options: "none", "bonferroni", "holm", "hochberg", "hommel", "BH", "BY", "fdr". Default: "fdr" (Benjamini-Hochberg False Discovery Rate). Applied to both tables and post-hoc tests. |
posthoc |
Logical. Compute post-hoc pairwise comparisons for 3+ groups? Default: TRUE. Results include a comparison table and text report. |
posthoc_method |
Method for post-hoc comparisons: "games-howell" (default, does not assume equal variances) or "tukey" (Tukey's HSD, assumes equal variances). |
posthoc_table |
Logical. Include detailed post-hoc pairwise comparison table in the output? Default FALSE. |
posthoc_format |
Character. Format for post-hoc table when pivot = TRUE: "wide" (default, comparisons as columns), "long" (one row per comparison), or "both" (return both formats). |
pairwise_display |
Which pairwise comparisons to show on plots? Options: "significant" (default), "all", "none". |
pivot |
Logical. Pivot to wide format? Default FALSE. When TRUE, creates a wide table based on pivot_by parameter. |
pivot_by |
Character. Which variable to pivot to columns: "category" (default) - category groups become columns (e.g., GPT, Mistral, Qwen), "repeat_category" - repeat_category levels become columns (e.g., he/him, she/her). |
pivot_stat |
Character. Statistic to display in pivoted cells: "mean" (default), "mean_sd" (mean with SD in parentheses), "median", or "n" (count). |
pivot_stars |
Logical. Show significance stars in pivot table? Default TRUE when pivot = TRUE. |
pivot_split_level |
Logical. When multiple repeat_category variables are combined (e.g., "he/him | High"), split them back into separate columns? Default TRUE. When FALSE, keeps the combined "level" column. |
min_threshold |
Numeric. Minimum proportion (0-1) of total sample required to include a repeat_category level. Default: 0.05 (5 percent). |
min_subcategory |
Integer. Minimum observations required per group. Groups with fewer observations are excluded from analysis. Default: 5. |
colors |
Character vector of colors for groups. Default: NULL uses a built-in palette. |
verbose |
Logical. Print progress messages? Default: TRUE. |
combined_table |
Logical. When 'repeat_category' is used, combine all results into a single table? Default: TRUE. The combined table shows all repeat_category levels together with bold highest means and red significant p-values. |
format |
Character. Output format for tables: "gt" (default, publication-ready), "plain" (data frame), "markdown", "latex", or "kable". |
show_header |
Logical. Show title/subtitle header? Default TRUE. Set to FALSE to hide the table header. |
interpret |
Logical. Pass results to AI for automatic interpretation?
Default FALSE. When TRUE, generates clean Methods and Results text using
AI. Requires API key setup (see |
... |
Additional arguments passed to |
A list with class "comparison_results" containing: plots (named list of ggplot objects), grid_plot (combined plot grid if multiple variables), summary_table (formatted gt table), and summary_data (data frame with raw statistics). For stratified analysis (with repeat_category), returns a named list where each element corresponds to a level of repeat_category. When pivot = TRUE, additional elements are returned:
pivot_table: gt table with groups as columns and factor levels as rows
posthoc_pivot_wide: Post-hoc comparisons in wide format (if posthoc_table = TRUE)
posthoc_pivot_long: Post-hoc comparisons in long format (if posthoc_format = "long" or "both")
ggbetweenstats for the underlying plot function
## Not run: # ============================================================ # EXAMPLE 1: Basic Two-Group Comparison (t-test) # ============================================================ data <- data.frame( gender = rep(c("Male", "Female"), each = 50), score = c(rnorm(50, mean = 100, sd = 15), rnorm(50, mean = 105, sd = 15)) ) results <- compare_groups( data = data, category = "gender", Vars = c("score") ) # View the plot results$plots$gender_vs_score # View summary statistics results$summary_data # ============================================================ # EXAMPLE 2: Three-Group Comparison (ANOVA with post-hoc) # ============================================================ data <- data.frame( country = rep(c("USA", "UK", "Germany"), each = 40), score1 = c(rnorm(40, 75, 10), rnorm(40, 70, 11), rnorm(40, 85, 9)), score2 = c(rnorm(40, 50, 8), rnorm(40, 55, 9), rnorm(40, 48, 7)) ) results <- compare_groups( data = data, category = "country", Vars = c("score1", "score2"), posthoc = TRUE, posthoc_method = "tukey", pairwise_display = "all" ) # View post-hoc pairwise comparisons results$summary_data$posthoc_results[[1]] # Print full ANOVA report cat(results$summary_data$anova_report[1]) # ============================================================ # EXAMPLE 3: Bayesian Analysis # ============================================================ results <- compare_groups( data = data, category = "country", Vars = c("score1"), bayesian = TRUE ) # View Bayes Factors results$summary_data[, c("country", "mean", "bf10", "bf_interpretation")] # ============================================================ # EXAMPLE 4: Nonparametric Tests # ============================================================ results <- compare_groups( data = data, category = "country", Vars = c("score1"), nonparametric = TRUE # Uses Kruskal-Wallis + pairwise Wilcoxon ) # ============================================================ # EXAMPLE 5: Stratified Analysis (separate tests per subgroup) # ============================================================ data <- data.frame( country = rep(c("USA", "UK", "Germany"), each = 60), gender = rep(c("Male", "Female"), times = 90), score = rnorm(180, mean = 100, sd = 15) ) # Compare gender WITHIN each country results <- compare_groups( data = data, category = "gender", Vars = c("score"), repeat_category = "country" ) # Access results by country results$USA$summary_data results$UK$plots$gender_vs_score results$Germany$summary_table # ============================================================ # EXAMPLE 6: Equivalence Testing (TOST) # ============================================================ results <- compare_groups( data = data, category = "gender", Vars = c("score"), equivalence = TRUE, equivalence_bounds = c(-0.3, 0.3) # Small effect bounds ) # Check equivalence conclusions results$summary_data[, c("gender", "mean", "equivalence_conclusion")] # ============================================================ # EXAMPLE 7: Combined/Interaction Groups # ============================================================ data <- data.frame( strength = rep(c("Strong", "Weak"), each = 60), gender = rep(c("Male", "Female"), times = 60), score = rnorm(120, mean = 100, sd = 15) ) # Pass multiple variables to category for interaction groups results <- compare_groups( data = data, category = c("strength", "gender"), # Creates "Strong | Male", "Strong | Female", etc. Vars = c("score") ) # Custom separator results <- compare_groups( data = data, category = c("strength", "gender"), category_sep = " x ", # Creates "Strong x Male", etc. Vars = c("score") ) # ============================================================ # EXAMPLE 8: Pivoted Table (groups as columns) # ============================================================ # LLM comparison data data <- data.frame( Support_level = c(rnorm(100, 4, 1), rnorm(100, 6.5, 1), rnorm(100, 4.8, 1)), pronoun = rep(c("he/him", "she/her", "they/them"), each = 100), LA_activity = rep(c("Negative", "Positive"), 150), llm = rep(c("GPT", "Mistral", "Qwen"), each = 100) ) # Basic pivot - groups become columns results <- compare_groups( data = data, category = "llm", # Becomes columns: GPT | Mistral | Qwen Vars = "Support_level", repeat_category = "pronoun", # Rows: he/him, she/her, they/them pivot = TRUE # Enable pivot mode ) # Access the pivot table results$pivot_table # ============================================================ # EXAMPLE 9: Pivot with Mean and SD # ============================================================ results <- compare_groups( data = data, category = "llm", Vars = "Support_level", repeat_category = c("pronoun", "LA_activity"), pivot = TRUE, pivot_stat = "mean_sd" # Shows "4.32 (1.21)" ) # ============================================================ # EXAMPLE 10: Pivot with Post-hoc Comparisons Table # ============================================================ results <- compare_groups( data = data, category = "llm", Vars = "Support_level", repeat_category = "pronoun", pivot = TRUE, posthoc = TRUE, posthoc_table = TRUE, # Include post-hoc table posthoc_format = "wide" # "wide", "long", or "both" ) # Access tables results$pivot_table # Main pivoted means table results$posthoc_pivot_wide # Post-hoc comparisons (wide format) # ============================================================ # EXAMPLE 11: Different P-value Adjustment Methods # ============================================================ # Available methods: "none", "bonferroni", "holm", "hochberg", # "hommel", "BH", "BY", "fdr" (default) results <- compare_groups( data = data, category = "llm", Vars = "Support_level", repeat_category = "pronoun", pivot = TRUE, p_adjust_method = "bonferroni" ) ## End(Not run)## Not run: # ============================================================ # EXAMPLE 1: Basic Two-Group Comparison (t-test) # ============================================================ data <- data.frame( gender = rep(c("Male", "Female"), each = 50), score = c(rnorm(50, mean = 100, sd = 15), rnorm(50, mean = 105, sd = 15)) ) results <- compare_groups( data = data, category = "gender", Vars = c("score") ) # View the plot results$plots$gender_vs_score # View summary statistics results$summary_data # ============================================================ # EXAMPLE 2: Three-Group Comparison (ANOVA with post-hoc) # ============================================================ data <- data.frame( country = rep(c("USA", "UK", "Germany"), each = 40), score1 = c(rnorm(40, 75, 10), rnorm(40, 70, 11), rnorm(40, 85, 9)), score2 = c(rnorm(40, 50, 8), rnorm(40, 55, 9), rnorm(40, 48, 7)) ) results <- compare_groups( data = data, category = "country", Vars = c("score1", "score2"), posthoc = TRUE, posthoc_method = "tukey", pairwise_display = "all" ) # View post-hoc pairwise comparisons results$summary_data$posthoc_results[[1]] # Print full ANOVA report cat(results$summary_data$anova_report[1]) # ============================================================ # EXAMPLE 3: Bayesian Analysis # ============================================================ results <- compare_groups( data = data, category = "country", Vars = c("score1"), bayesian = TRUE ) # View Bayes Factors results$summary_data[, c("country", "mean", "bf10", "bf_interpretation")] # ============================================================ # EXAMPLE 4: Nonparametric Tests # ============================================================ results <- compare_groups( data = data, category = "country", Vars = c("score1"), nonparametric = TRUE # Uses Kruskal-Wallis + pairwise Wilcoxon ) # ============================================================ # EXAMPLE 5: Stratified Analysis (separate tests per subgroup) # ============================================================ data <- data.frame( country = rep(c("USA", "UK", "Germany"), each = 60), gender = rep(c("Male", "Female"), times = 90), score = rnorm(180, mean = 100, sd = 15) ) # Compare gender WITHIN each country results <- compare_groups( data = data, category = "gender", Vars = c("score"), repeat_category = "country" ) # Access results by country results$USA$summary_data results$UK$plots$gender_vs_score results$Germany$summary_table # ============================================================ # EXAMPLE 6: Equivalence Testing (TOST) # ============================================================ results <- compare_groups( data = data, category = "gender", Vars = c("score"), equivalence = TRUE, equivalence_bounds = c(-0.3, 0.3) # Small effect bounds ) # Check equivalence conclusions results$summary_data[, c("gender", "mean", "equivalence_conclusion")] # ============================================================ # EXAMPLE 7: Combined/Interaction Groups # ============================================================ data <- data.frame( strength = rep(c("Strong", "Weak"), each = 60), gender = rep(c("Male", "Female"), times = 60), score = rnorm(120, mean = 100, sd = 15) ) # Pass multiple variables to category for interaction groups results <- compare_groups( data = data, category = c("strength", "gender"), # Creates "Strong | Male", "Strong | Female", etc. Vars = c("score") ) # Custom separator results <- compare_groups( data = data, category = c("strength", "gender"), category_sep = " x ", # Creates "Strong x Male", etc. Vars = c("score") ) # ============================================================ # EXAMPLE 8: Pivoted Table (groups as columns) # ============================================================ # LLM comparison data data <- data.frame( Support_level = c(rnorm(100, 4, 1), rnorm(100, 6.5, 1), rnorm(100, 4.8, 1)), pronoun = rep(c("he/him", "she/her", "they/them"), each = 100), LA_activity = rep(c("Negative", "Positive"), 150), llm = rep(c("GPT", "Mistral", "Qwen"), each = 100) ) # Basic pivot - groups become columns results <- compare_groups( data = data, category = "llm", # Becomes columns: GPT | Mistral | Qwen Vars = "Support_level", repeat_category = "pronoun", # Rows: he/him, she/her, they/them pivot = TRUE # Enable pivot mode ) # Access the pivot table results$pivot_table # ============================================================ # EXAMPLE 9: Pivot with Mean and SD # ============================================================ results <- compare_groups( data = data, category = "llm", Vars = "Support_level", repeat_category = c("pronoun", "LA_activity"), pivot = TRUE, pivot_stat = "mean_sd" # Shows "4.32 (1.21)" ) # ============================================================ # EXAMPLE 10: Pivot with Post-hoc Comparisons Table # ============================================================ results <- compare_groups( data = data, category = "llm", Vars = "Support_level", repeat_category = "pronoun", pivot = TRUE, posthoc = TRUE, posthoc_table = TRUE, # Include post-hoc table posthoc_format = "wide" # "wide", "long", or "both" ) # Access tables results$pivot_table # Main pivoted means table results$posthoc_pivot_wide # Post-hoc comparisons (wide format) # ============================================================ # EXAMPLE 11: Different P-value Adjustment Methods # ============================================================ # Available methods: "none", "bonferroni", "holm", "hochberg", # "hommel", "BH", "BY", "fdr" (default) results <- compare_groups( data = data, category = "llm", Vars = "Support_level", repeat_category = "pronoun", pivot = TRUE, p_adjust_method = "bonferroni" ) ## End(Not run)
Performs Network Comparison Test (NCT) to compare network structure and global strength between two groups.
compare_networks(results, groups, it = 1000, test = "both", verbose = TRUE)compare_networks(results, groups, it = 1000, test = "both", verbose = TRUE)
results |
Object from estimate_grouped_networks |
groups |
Character vector of length 2 specifying which groups to compare |
it |
Number of permutations for NCT. Defaults to 1000. |
test |
Which tests to perform: "network" (structure), "global" (strength), "both" (default). |
verbose |
Print progress. Defaults to TRUE. |
A list containing NCT results with p-values for network structure and global strength differences.
## Not run: # First estimate grouped networks grouped_results <- estimate_grouped_networks(df, Vars, GroupVar = "group") # Then compare two groups comparison <- compare_networks( grouped_results, groups = c("GroupA", "GroupB"), it = 500 ) ## End(Not run)## Not run: # First estimate grouped networks grouped_results <- estimate_grouped_networks(df, Vars, GroupVar = "group") # Then compare two groups comparison <- compare_networks( grouped_results, groups = c("GroupA", "GroupB"), it = 500 ) ## End(Not run)
Converts long-form or wide-form sequence data into useful formats for analysis, such as frequency tables, one-hot encodings, or edge lists (for network analysis).
convert_sequences( data, seq_cols = NULL, id_col = NULL, format = c("frequency", "onehot", "edgelist", "follows"), na_values = NULL )convert_sequences( data, seq_cols = NULL, id_col = NULL, format = c("frequency", "onehot", "edgelist", "follows"), na_values = NULL )
data |
A data frame containing sequence data. |
seq_cols |
Character vector of sequence column names. If NULL (default), auto-detects all columns except the ID column. |
id_col |
Character. Name of the ID column. If NULL (default), uses the first column. |
format |
Character. Output format:
|
na_values |
Character vector of values to treat as missing/NA. Default includes: NA, NaN, "", "*", " TraMineR typically uses "*" for missing states. |
A data frame structured according to the requested format:
'frequency': Wide format with action counts per ID
'onehot': Wide format with binary indicators per ID
'edgelist': Long format with columns: id, from, to
'follows': Long format with columns: id, act, follows
## Not run: # Example sequence data seq_data <- data.frame( id = 1:3, t1 = c("A", "B", "A"), t2 = c("B", "A", "C"), t3 = c("C", "C", "A"), t4 = c("A", "*", "B") # "*" is TraMineR missing ) # Frequency table convert_sequences(seq_data, format = "frequency") # One-hot encoding convert_sequences(seq_data, format = "onehot") # Edge list for network analysis convert_sequences(seq_data, format = "edgelist") # What follows what convert_sequences(seq_data, format = "follows") ## End(Not run)## Not run: # Example sequence data seq_data <- data.frame( id = 1:3, t1 = c("A", "B", "A"), t2 = c("B", "A", "C"), t3 = c("C", "C", "A"), t4 = c("A", "*", "B") # "*" is TraMineR missing ) # Frequency table convert_sequences(seq_data, format = "frequency") # One-hot encoding convert_sequences(seq_data, format = "onehot") # Edge list for network analysis convert_sequences(seq_data, format = "edgelist") # What follows what convert_sequences(seq_data, format = "follows") ## End(Not run)
Creates a formatted correlation matrix with significance stars, optional confidence intervals, and heatmap visualization. Supports bivariate (zero-order), partial, and semi-partial correlations.
correlation_matrix( data, Vars = NULL, type = c("bivariate", "partial", "semi-partial"), method = c("pearson", "spearman", "kendall"), triangle = c("lower", "upper", "full"), diagonal = c("dash", "one", "names"), show_n = FALSE, show_ci = FALSE, show_p = FALSE, p_adjust = c("none", "bonferroni", "holm", "fdr"), stars = TRUE, heatmap = FALSE, digits = 2, title = NULL, use = c("pairwise", "complete"), format = c("gt", "plain", "markdown", "latex", "kable"), show_header = TRUE, interpret = FALSE, ... )correlation_matrix( data, Vars = NULL, type = c("bivariate", "partial", "semi-partial"), method = c("pearson", "spearman", "kendall"), triangle = c("lower", "upper", "full"), diagonal = c("dash", "one", "names"), show_n = FALSE, show_ci = FALSE, show_p = FALSE, p_adjust = c("none", "bonferroni", "holm", "fdr"), stars = TRUE, heatmap = FALSE, digits = 2, title = NULL, use = c("pairwise", "complete"), format = c("gt", "plain", "markdown", "latex", "kable"), show_header = TRUE, interpret = FALSE, ... )
data |
A data frame containing the variables to correlate. |
Vars |
Character vector of variable names to include in the correlation matrix. If NULL (default), all numeric variables in the data frame are used. |
type |
Type of correlation: "bivariate" (default, zero-order), "partial", or "semi-partial". For partial/semi-partial, each pair is controlled for all other variables in Vars. |
method |
Correlation method: "pearson" (default), "spearman", or "kendall". |
triangle |
Which triangle to display: "lower" (default), "upper", or "full". |
diagonal |
What to show on the diagonal: "dash" (default), "one", or "names". |
show_n |
Logical. Show pairwise sample sizes? Default FALSE. |
show_ci |
Logical. Show 95 percent confidence intervals? Default FALSE. Only available for bivariate Pearson. |
show_p |
Logical. Show p-values below correlations? Default FALSE. |
p_adjust |
Method for p-value adjustment: "none" (default), "bonferroni", "holm", "fdr". |
stars |
Logical. Show significance stars? Default TRUE. |
heatmap |
Logical. Create a heatmap visualization? Default FALSE. |
digits |
Number of decimal places. Default 2. |
title |
Optional title for the table. |
use |
Method for handling missing data: "pairwise" (default) or "complete". Note: partial and semi-partial correlations always use complete cases. |
format |
Character. Output format: "gt" (default, publication-ready gt table), "plain" (data frame), "markdown", "latex", or "kable". |
show_header |
Logical. Show title header? Default: 'TRUE'. Set to 'FALSE' to hide the table header. |
interpret |
Logical. Pass results to AI for automatic interpretation?
Default FALSE. When TRUE, generates clean Methods and Results text using
AI. Requires API key setup (see |
... |
Additional arguments passed to |
A list containing: table (gt table with formatted correlations), correlation_matrix (numeric matrix), p_matrix (matrix of p-values), n_matrix (pairwise sample sizes), and heatmap (ggplot if requested).
## Not run: # Basic correlation matrix correlation_matrix( data = mtcars, Vars = c("mpg", "cyl", "disp", "hp") ) # Partial correlations (controlling for other variables) correlation_matrix( data = mtcars, Vars = c("mpg", "cyl", "disp", "hp"), type = "partial", title = "Partial Correlations" ) # Semi-partial correlations correlation_matrix( data = mtcars, Vars = c("mpg", "cyl", "disp", "hp"), type = "semi-partial" ) # With confidence intervals and heatmap correlation_matrix( data = mtcars, Vars = c("mpg", "cyl", "disp", "hp"), show_ci = TRUE, heatmap = TRUE, title = "Motor Trend Car Correlations" ) # Spearman correlations with Bonferroni correction correlation_matrix( data = mtcars, Vars = c("mpg", "cyl", "disp"), method = "spearman", p_adjust = "bonferroni" ) ## End(Not run)## Not run: # Basic correlation matrix correlation_matrix( data = mtcars, Vars = c("mpg", "cyl", "disp", "hp") ) # Partial correlations (controlling for other variables) correlation_matrix( data = mtcars, Vars = c("mpg", "cyl", "disp", "hp"), type = "partial", title = "Partial Correlations" ) # Semi-partial correlations correlation_matrix( data = mtcars, Vars = c("mpg", "cyl", "disp", "hp"), type = "semi-partial" ) # With confidence intervals and heatmap correlation_matrix( data = mtcars, Vars = c("mpg", "cyl", "disp", "hp"), show_ci = TRUE, heatmap = TRUE, title = "Motor Trend Car Correlations" ) # Spearman correlations with Bonferroni correction correlation_matrix( data = mtcars, Vars = c("mpg", "cyl", "disp"), method = "spearman", p_adjust = "bonferroni" ) ## End(Not run)
Creates a comprehensive long-format correlation table showing all pairwise correlations with full statistics including r, confidence intervals, test statistics, degrees of freedom, p-values, and sample sizes. Supports multilevel/repeated measures correlations for nested data.
correlations( data, Vars = NULL, type = c("bivariate", "partial", "semi-partial"), method = c("pearson", "spearman", "kendall"), p_adjust = c("none", "bonferroni", "holm", "fdr"), ci_level = 0.95, min_r = NULL, sig_only = FALSE, multilevel = FALSE, id = NULL, between = FALSE, group_by = NULL, include = NULL, exclude = NULL, auto_consolidate = TRUE, digits = 3, title = NULL, format = c("gt", "plain", "markdown", "latex", "kable"), show_header = TRUE, interpret = FALSE, ... )correlations( data, Vars = NULL, type = c("bivariate", "partial", "semi-partial"), method = c("pearson", "spearman", "kendall"), p_adjust = c("none", "bonferroni", "holm", "fdr"), ci_level = 0.95, min_r = NULL, sig_only = FALSE, multilevel = FALSE, id = NULL, between = FALSE, group_by = NULL, include = NULL, exclude = NULL, auto_consolidate = TRUE, digits = 3, title = NULL, format = c("gt", "plain", "markdown", "latex", "kable"), show_header = TRUE, interpret = FALSE, ... )
data |
A data frame containing the variables to correlate. |
Vars |
Character vector of variable names to include. If NULL (default), all numeric variables in the data frame are used. |
type |
Type of correlation: "bivariate" (default), "partial", or "semi-partial". |
method |
Correlation method: "pearson" (default), "spearman", or "kendall". |
p_adjust |
Method for p-value adjustment: "none" (default), "bonferroni", "holm", "fdr". |
ci_level |
Confidence level for intervals. Default 0.95. |
min_r |
Numeric. Only show correlations with |r| >= this value. Default NULL (show all). |
sig_only |
Logical. Only show significant correlations (p < .05)? Default FALSE. |
multilevel |
Logical. Calculate multilevel (within-cluster) correlations? Default FALSE. When TRUE, removes between-cluster variance to estimate within-cluster associations. |
id |
Character. Name of the clustering/ID variable for multilevel correlations. Required when multilevel = TRUE. |
between |
Logical. Also report between-cluster correlations? Default FALSE. Only used when multilevel = TRUE. |
group_by |
Character. Name of grouping variable to compute correlations separately per group. Results are combined into one table with a "Group" column. |
include |
Character vector. Statistics to include in the table. Options: "r", "ci", "stat" (t/S/z), "df", "p", "n", "sig". Default NULL includes all. Use this OR exclude, not both. |
exclude |
Character vector. Statistics to exclude from the table. Options: "r", "ci", "stat" (t/S/z), "df", "p", "n", "sig". Default NULL excludes none. Use this OR include, not both. |
auto_consolidate |
Logical. If TRUE (default), when df or n are constant across all pairs, they are moved to the subtitle instead of shown as columns. |
digits |
Number of decimal places. Default 3. |
title |
Optional title for the table. |
format |
Character. Output format: "gt" (default, publication-ready gt table), "plain" (data frame), "markdown", "latex", or "kable". |
show_header |
Logical. Show title/subtitle header? Default TRUE. Set to FALSE to hide the table header. |
interpret |
Logical. Pass results to AI for automatic interpretation?
Default FALSE. When TRUE, generates clean Methods and Results text using
AI. Requires API key setup (see |
... |
Additional arguments passed to |
When multilevel = TRUE, the function calculates within-cluster correlations
by group-mean centering variables before computing correlations. This removes
between-cluster variance and estimates the pooled within-cluster association,
appropriate for repeated measures or hierarchically nested data.
The degrees of freedom for multilevel correlations are adjusted as: df = n_observations - n_clusters - 1
A list containing: table (formatted output), data (raw statistics), display (formatted display data frame), n_pairs, n_significant, consolidated (values moved to subtitle), between_data (if multilevel).
## Not run: # Correlate all numeric variables in data frame correlations(mtcars) # Full correlation table with specific variables correlations(mtcars, Vars = c("mpg", "cyl", "disp", "hp", "wt")) # Only strong correlations correlations(mtcars, Vars = c("mpg", "cyl", "disp", "hp"), min_r = 0.5) # Partial correlations with Bonferroni correction correlations(mtcars, Vars = c("mpg", "cyl", "disp", "hp"), type = "partial", p_adjust = "bonferroni") # Only significant correlations correlations(mtcars, Vars = c("mpg", "cyl", "disp", "hp", "wt"), sig_only = TRUE) # Multilevel correlations (within-person) correlations(longitudinal_data, Vars = c("anxiety", "depression", "stress"), multilevel = TRUE, id = "participant_id") # Multilevel with between-cluster correlations correlations(longitudinal_data, Vars = c("anxiety", "depression"), multilevel = TRUE, id = "participant_id", between = TRUE) # Correlations by group (stratified) correlations(mtcars, Vars = c("mpg", "hp", "wt"), group_by = "cyl") # Correlations by group with significance filter correlations(mtcars, Vars = c("mpg", "hp", "wt", "disp"), group_by = "am", sig_only = TRUE) # Include only specific statistics correlations(mtcars, Vars = c("mpg", "hp", "wt"), include = c("r", "ci", "p", "sig")) # Exclude statistics you don't need correlations(mtcars, Vars = c("mpg", "hp", "wt"), exclude = c("stat", "df")) # Disable auto-consolidation (always show df and n columns) correlations(mtcars, Vars = c("mpg", "hp", "wt"), auto_consolidate = FALSE) ## End(Not run)## Not run: # Correlate all numeric variables in data frame correlations(mtcars) # Full correlation table with specific variables correlations(mtcars, Vars = c("mpg", "cyl", "disp", "hp", "wt")) # Only strong correlations correlations(mtcars, Vars = c("mpg", "cyl", "disp", "hp"), min_r = 0.5) # Partial correlations with Bonferroni correction correlations(mtcars, Vars = c("mpg", "cyl", "disp", "hp"), type = "partial", p_adjust = "bonferroni") # Only significant correlations correlations(mtcars, Vars = c("mpg", "cyl", "disp", "hp", "wt"), sig_only = TRUE) # Multilevel correlations (within-person) correlations(longitudinal_data, Vars = c("anxiety", "depression", "stress"), multilevel = TRUE, id = "participant_id") # Multilevel with between-cluster correlations correlations(longitudinal_data, Vars = c("anxiety", "depression"), multilevel = TRUE, id = "participant_id", between = TRUE) # Correlations by group (stratified) correlations(mtcars, Vars = c("mpg", "hp", "wt"), group_by = "cyl") # Correlations by group with significance filter correlations(mtcars, Vars = c("mpg", "hp", "wt", "disp"), group_by = "am", sig_only = TRUE) # Include only specific statistics correlations(mtcars, Vars = c("mpg", "hp", "wt"), include = c("r", "ci", "p", "sig")) # Exclude statistics you don't need correlations(mtcars, Vars = c("mpg", "hp", "wt"), exclude = c("stat", "df")) # Disable auto-consolidation (always show df and n columns) correlations(mtcars, Vars = c("mpg", "hp", "wt"), auto_consolidate = FALSE) ## End(Not run)
Converts long-format event data to a frequency table with counts per ID. Useful for transforming event logs, clickstream data, or any repeated measures into a wide format suitable for analysis.
counts(data, id = NULL, event = NULL, na_values = NULL)counts(data, id = NULL, event = NULL, na_values = NULL)
data |
A data frame containing event data in long format. |
id |
Character vector. Name(s) of ID column(s). If multiple IDs are provided, they are combined. If NULL (default), uses the first column. |
event |
Character. Name of the event/action column to count. If NULL (default), uses the second column. |
na_values |
Character vector of values to treat as missing. Default includes common missing indicators. |
A data frame with one row per unique ID combination and columns for each unique event value containing counts.
## Not run: # Event log data events <- data.frame( student = c(1, 1, 1, 2, 2, 2, 3, 3), action = c("login", "view", "submit", "login", "view", "view", "login", "submit") ) # Count events per student counts(events, id = "student", event = "action") # Multiple ID columns events2 <- data.frame( student = c(1, 1, 1, 1, 2, 2), course = c("A", "A", "B", "B", "A", "A"), action = c("view", "submit", "view", "view", "view", "submit") ) counts(events2, id = c("student", "course"), event = "action") ## End(Not run)## Not run: # Event log data events <- data.frame( student = c(1, 1, 1, 2, 2, 2, 3, 3), action = c("login", "view", "submit", "login", "view", "view", "login", "submit") ) # Count events per student counts(events, id = "student", event = "action") # Multiple ID columns events2 <- data.frame( student = c(1, 1, 1, 1, 2, 2), course = c("A", "A", "B", "B", "A", "A"), action = c("view", "submit", "view", "view", "view", "submit") ) counts(events2, id = c("student", "course"), event = "action") ## End(Not run)
Provides a comprehensive snapshot of a dataset including variable types, missing data percentages, unique values, and basic statistics.
data_overview(data, Vars = NULL, max_levels = 10, digits = 2)data_overview(data, Vars = NULL, max_levels = 10, digits = 2)
data |
A data frame to summarize. |
Vars |
Character vector of variable names. If NULL (default), all variables are included. |
max_levels |
Integer. For categorical variables, show level counts if <= this value. Default 10. |
digits |
Integer. Number of decimal places for numeric summaries. Default 2. |
A gt table with dataset overview.
## Not run: data_overview(mtcars) data_overview(iris, Vars = c("Sepal.Length", "Species")) ## End(Not run)## Not run: data_overview(mtcars) data_overview(iris, Vars = c("Sepal.Length", "Species")) ## End(Not run)
Creates a comprehensive, publication-ready table of descriptive statistics for numeric variables. Supports stratification by grouping variables and outputs beautifully formatted gt tables.
descriptive_table( data, Vars = NULL, group_by = NULL, stats = c("n", "mean", "sd", "median", "min", "max"), digits = 2, labels = NULL, title = "Descriptive Statistics", subtitle = NULL, overall = FALSE, transpose = FALSE, format = c("gt", "plain", "markdown", "latex", "kable"), show_header = TRUE, theme = "default", compare = FALSE, bold_highest = NULL, sig_color = "red", interpret = FALSE, ... )descriptive_table( data, Vars = NULL, group_by = NULL, stats = c("n", "mean", "sd", "median", "min", "max"), digits = 2, labels = NULL, title = "Descriptive Statistics", subtitle = NULL, overall = FALSE, transpose = FALSE, format = c("gt", "plain", "markdown", "latex", "kable"), show_header = TRUE, theme = "default", compare = FALSE, bold_highest = NULL, sig_color = "red", interpret = FALSE, ... )
data |
A data frame containing the variables to summarize. |
Vars |
Column specification for variables to describe. Can be NULL (default, all numeric columns), a character vector of column names, a numeric vector of column indices, or a single number (from that column to end). |
group_by |
Optional character. Name of a grouping variable for stratified statistics. When provided, statistics are calculated separately for each group level. |
stats |
Character vector specifying which statistics to compute. Default: c("n", "mean", "sd", "median", "min", "max"). Available options: "n", "missing", "missing_pct", "mean", "sd", "se", "var", "median", "min", "max", "range", "iqr", "q1", "q3", "skewness", "kurtosis", "cv". |
digits |
Integer. Number of decimal places for numeric output. Default: '2'. |
labels |
Optional named character vector for variable labels. Example: 'c(age = "Age (years)", score1 = "Test Score")'. If NULL, variable names are used as-is. |
title |
Optional character string for table title. Default: '"Descriptive Statistics"'. |
subtitle |
Optional character string for table subtitle. |
overall |
Logical. When 'group_by' is specified, also include overall (ungrouped) statistics? Default: FALSE. |
transpose |
Logical. Transpose the table so variables are columns and statistics are rows? Default: FALSE. |
format |
Character. Output format: "gt" (default, publication-ready gt table), "plain" (data frame), "markdown", "latex", or "kable". |
show_header |
Logical. Show title/subtitle header? Default TRUE. Set to FALSE to hide the table header. |
theme |
Character. Visual theme for gt table: "default" (clean scientific style), "fancy" (blue with striped rows), "minimal" (bottom border only), "dark" (dark background), or "colorful" (purple accents). Default: "default". |
compare |
Logical. When 'group_by' is specified, run statistical tests (t-test for 2 groups, ANOVA for 3+ groups) and report p-values and effect sizes? Default: FALSE. |
bold_highest |
Logical. When 'group_by' is specified, bold the highest mean for each variable? Default: TRUE when compare is 'TRUE'. |
sig_color |
Character. Color for significant p-values (< 0.05). Default: '"red"'. Set to 'NULL' to disable coloring. |
interpret |
Logical. Pass results to AI for automatic interpretation?
Default FALSE. When TRUE, generates clean Methods and Results text using
AI. Requires API key setup (see |
... |
Additional arguments passed to |
A saqr_result object containing:
table: The formatted gt table (or other format if specified)
data: Raw data frame with computed statistics
markdown: Markdown version of the table for AI interpretation
type: "descriptive"
variables: Variables analyzed
statistics: Statistics computed
n: Total sample size
When printed, displays the formatted table. Use result$markdown to
get a text version suitable for pass.
The gt output can be exported using gtsave(): HTML (.html), Word (.docx), PDF (.pdf), or PNG (.png). Example: gtsave(table, "descriptives.html").
gt for gt table customization
## Not run: # ============================================================ # EXAMPLE 1: Basic Descriptive Statistics # ============================================================ data <- data.frame( age = rnorm(100, mean = 35, sd = 10), score = rnorm(100, mean = 75, sd = 15), income = rnorm(100, mean = 50000, sd = 15000) ) # Default statistics (n, mean, sd, median, min, max) descriptive_table(data, Vars = c("age", "score", "income")) # ============================================================ # EXAMPLE 2: Custom Statistics Selection # ============================================================ descriptive_table( data = data, Vars = c("age", "score"), stats = c("n", "mean", "sd", "se", "median", "iqr", "skewness", "kurtosis") ) # ============================================================ # EXAMPLE 3: Stratified by Group # ============================================================ data$gender <- sample(c("Male", "Female"), 100, replace = TRUE) descriptive_table( data = data, Vars = c("age", "score"), group_by = gender, overall = TRUE # Include overall statistics ) # ============================================================ # EXAMPLE 4: Custom Labels and Title # ============================================================ descriptive_table( data = data, Vars = c("age", "score", "income"), labels = c( age = "Age (years)", score = "Test Score", income = "Annual Income ($)" ), title = "Sample Characteristics", subtitle = "N = 100 participants" ) # ============================================================ # EXAMPLE 5: Export to Data Frame # ============================================================ df <- descriptive_table( data = data, Vars = c("age", "score"), format = "data.frame" ) print(df) # ============================================================ # EXAMPLE 6: Different Themes # ============================================================ descriptive_table(data, Vars = c("age", "score"), theme = "minimal") descriptive_table(data, Vars = c("age", "score"), theme = "dark") descriptive_table(data, Vars = c("age", "score"), theme = "colorful") ## End(Not run)## Not run: # ============================================================ # EXAMPLE 1: Basic Descriptive Statistics # ============================================================ data <- data.frame( age = rnorm(100, mean = 35, sd = 10), score = rnorm(100, mean = 75, sd = 15), income = rnorm(100, mean = 50000, sd = 15000) ) # Default statistics (n, mean, sd, median, min, max) descriptive_table(data, Vars = c("age", "score", "income")) # ============================================================ # EXAMPLE 2: Custom Statistics Selection # ============================================================ descriptive_table( data = data, Vars = c("age", "score"), stats = c("n", "mean", "sd", "se", "median", "iqr", "skewness", "kurtosis") ) # ============================================================ # EXAMPLE 3: Stratified by Group # ============================================================ data$gender <- sample(c("Male", "Female"), 100, replace = TRUE) descriptive_table( data = data, Vars = c("age", "score"), group_by = gender, overall = TRUE # Include overall statistics ) # ============================================================ # EXAMPLE 4: Custom Labels and Title # ============================================================ descriptive_table( data = data, Vars = c("age", "score", "income"), labels = c( age = "Age (years)", score = "Test Score", income = "Annual Income ($)" ), title = "Sample Characteristics", subtitle = "N = 100 participants" ) # ============================================================ # EXAMPLE 5: Export to Data Frame # ============================================================ df <- descriptive_table( data = data, Vars = c("age", "score"), format = "data.frame" ) print(df) # ============================================================ # EXAMPLE 6: Different Themes # ============================================================ descriptive_table(data, Vars = c("age", "score"), theme = "minimal") descriptive_table(data, Vars = c("age", "score"), theme = "dark") descriptive_table(data, Vars = c("age", "score"), theme = "colorful") ## End(Not run)
Estimates networks for different groups within a data frame, using 'estimate_single_network' internally. Produces separate network visualizations and metrics for each group.
estimate_grouped_networks( df, Vars = NULL, GroupVar, layout = "circle", color = DEFAULT_NODE_COLOR, default = "EBICglasso", var_types = NULL, qgraph_args = list(), network_args = list(), verbose = TRUE, min_group_size = 30 )estimate_grouped_networks( df, Vars = NULL, GroupVar, layout = "circle", color = DEFAULT_NODE_COLOR, default = "EBICglasso", var_types = NULL, qgraph_args = list(), network_args = list(), verbose = TRUE, min_group_size = 30 )
df |
A data frame containing the variables and group variable. |
Vars |
Character vector of variable names to include in the network. If NULL (default), all columns except GroupVar are used. |
GroupVar |
Character string specifying the grouping variable name. |
layout |
Layout algorithm for network plots. Defaults to "circle". |
color |
Node color(s). Defaults to "#EEEEEE". |
default |
Network estimation method. Defaults to "EBICglasso". |
var_types |
Variable types for MGM. If NULL, auto-detected. |
qgraph_args |
Additional arguments for qgraph. |
network_args |
Additional arguments for bootnet::estimateNetwork. |
verbose |
Print progress messages. Defaults to TRUE. |
min_group_size |
Minimum group size required. Groups with fewer observations are skipped. Defaults to 30. |
A list of class "grouped_network_analysis" containing:
networks: List of network objects per group
network_matrices: List of adjacency matrices per group
predictions: List of prediction results per group
centralities: List of centrality measures per group
qgraphs: List of qgraph plot objects per group
group_sizes: Sample sizes per group
failed_groups: Groups that failed estimation
## Not run: # Estimate networks by group results <- estimate_grouped_networks( df = my_data, Vars = c("var1", "var2", "var3", "var4"), GroupVar = "group" ) # Access results for specific group results$networks$GroupA results$predictions$GroupA # Compare networks compare_networks(results, groups = c("GroupA", "GroupB")) ## End(Not run)## Not run: # Estimate networks by group results <- estimate_grouped_networks( df = my_data, Vars = c("var1", "var2", "var3", "var4"), GroupVar = "group" ) # Access results for specific group results$networks$GroupA results$predictions$GroupA # Compare networks compare_networks(results, groups = c("GroupA", "GroupB")) ## End(Not run)
Estimates a single psychological network from a data frame using regularized partial correlations (via bootnet) and Mixed Graphical Models (via mgm). Provides network visualization with predictability metrics (R-squared pie charts).
estimate_single_network( df, Vars = NULL, layout = "circle", color = DEFAULT_NODE_COLOR, title = "Between-person network", default = "EBICglasso", var_types = NULL, qgraph_args = list(), network_args = list(), verbose = TRUE, compute_centrality = TRUE )estimate_single_network( df, Vars = NULL, layout = "circle", color = DEFAULT_NODE_COLOR, title = "Between-person network", default = "EBICglasso", var_types = NULL, qgraph_args = list(), network_args = list(), verbose = TRUE, compute_centrality = TRUE )
df |
A data frame containing the variables to be analyzed. |
Vars |
A character vector specifying the names of variables to include. If NULL (default), all columns of the data frame are used. |
layout |
Character string specifying the layout algorithm for the network plot. Options: "circle", "spring", "groups", etc. Defaults to "circle". |
color |
Character string or vector specifying node colors. Defaults to "#EEEEEE". |
title |
Title for the network plot. Defaults to "Between-person network". |
default |
Network estimation method for bootnet::estimateNetwork. Options: "EBICglasso" (default), "ggmModSelect", "pcor", etc. |
var_types |
Character vector of variable types for MGM ("g" = Gaussian, "c" = categorical, "p" = Poisson). If NULL (default), types are auto-detected. |
qgraph_args |
List of additional arguments passed to qgraph::qgraph. |
network_args |
List of additional arguments passed to bootnet::estimateNetwork. |
verbose |
Logical. If TRUE, prints progress messages. Defaults to TRUE. |
compute_centrality |
Logical. If TRUE, computes centrality measures. Defaults to TRUE. |
A list of class "network_analysis" containing:
network_object: Full network object from bootnet
network_matrix: Adjacency/weight matrix
prediction: MGM prediction results (R2, RMSE)
centrality: Centrality measures (if compute_centrality = TRUE)
qgraph: The qgraph plot object
var_types: Variable types used for MGM
## Not run: # Basic usage result <- estimate_single_network( df = my_data, Vars = c("var1", "var2", "var3", "var4", "var5") ) # Access network matrix result$network_matrix # View predictability result$prediction # View centrality result$centrality # Custom settings result <- estimate_single_network( df = my_data, Vars = c("var1", "var2", "var3"), layout = "spring", default = "ggmModSelect", var_types = c("g", "g", "c"), # Manual type specification verbose = FALSE ) ## End(Not run)## Not run: # Basic usage result <- estimate_single_network( df = my_data, Vars = c("var1", "var2", "var3", "var4", "var5") ) # Access network matrix result$network_matrix # View predictability result$prediction # View centrality result$centrality # Custom settings result <- estimate_single_network( df = my_data, Vars = c("var1", "var2", "var3"), layout = "spring", default = "ggmModSelect", var_types = c("g", "g", "c"), # Manual type specification verbose = FALSE ) ## End(Not run)
Input Data with Profile Assignments
## S3 method for class 'saqr_clustering' fitted(object, ...)## S3 method for class 'saqr_clustering' fitted(object, ...)
object |
A 'saqr_clustering' object from [clustering()]. |
... |
Ignored. |
The data frame passed to [clustering()], one row per input row, with 'profile' (modal assignment), 'uncertainty' and one 'posterior_profile_<k>' column per profile added. Rows dropped for missing values carry 'NA' in the added columns.
Vectorized function to detect outliers for use with dplyr. For group-wise detection, use dplyr::group_by() before mutate().
is_outlier( x, method = c("zscore", "iqr", "percentile"), threshold = NULL, na.rm = TRUE )is_outlier( x, method = c("zscore", "iqr", "percentile"), threshold = NULL, na.rm = TRUE )
x |
Numeric vector. |
method |
Detection method: "zscore", "iqr", or "percentile". |
threshold |
Threshold value. |
na.rm |
Logical. Remove NA values? Default TRUE. |
Logical vector indicating outliers.
## Not run: library(dplyr) # Flag outliers beyond 2 SD mtcars %>% mutate(hp_outlier = is_outlier(hp, method = "zscore", threshold = 2)) # Flag outliers at 5th/95th percentile mtcars %>% mutate(hp_outlier = is_outlier(hp, method = "percentile", threshold = 0.05)) # Group-wise outlier detection mtcars %>% group_by(cyl) %>% mutate(hp_outlier = is_outlier(hp)) ## End(Not run)## Not run: library(dplyr) # Flag outliers beyond 2 SD mtcars %>% mutate(hp_outlier = is_outlier(hp, method = "zscore", threshold = 2)) # Flag outliers at 5th/95th percentile mtcars %>% mutate(hp_outlier = is_outlier(hp, method = "percentile", threshold = 0.05)) # Group-wise outlier detection mtcars %>% group_by(cyl) %>% mutate(hp_outlier = is_outlier(hp)) ## End(Not run)
Opens an interactive Shiny application for mosaic_analysis.
Upload a CSV (or use the built-in demo), pick two categorical variables,
and explore the chi-square / Fisher test, Cramer's V effect size,
standardized residuals, and the shaded mosaic plot. Every
mosaic_analysis() option is exposed in the sidebar.
Requires the shiny and DT packages.
launch_app(...)launch_app(...)
... |
Passed to |
Called for its side effect (launches the app). No return value.
if (interactive()) { launch_app() }if (interactive()) { launch_app() }
Provides comprehensive missing data analysis including patterns, Little's MCAR test, and visualizations.
missing_analysis( data, Vars = NULL, pattern_plot = TRUE, mcar_test = TRUE, correlations = FALSE, digits = 2 )missing_analysis( data, Vars = NULL, pattern_plot = TRUE, mcar_test = TRUE, correlations = FALSE, digits = 2 )
data |
A data frame to analyze. |
Vars |
Character vector of variable names. If NULL (default), all variables are included. |
pattern_plot |
Logical. Create missing data pattern visualization? Default TRUE. |
mcar_test |
Logical. Perform Little's MCAR test? Default TRUE. |
correlations |
Logical. Show correlations between missingness indicators? Default FALSE. |
digits |
Integer. Number of decimal places. Default 2. |
A list containing:
summary: gt table with missing data summary
patterns: Data frame of missing patterns
mcar: MCAR test results (if requested)
plot: Missing pattern plot (if requested)
## Not run: # Create data with missing values df <- mtcars df$mpg[c(1, 5, 10)] <- NA df$hp[c(2, 5, 15)] <- NA missing_analysis(df) ## End(Not run)## Not run: # Create data with missing values df <- mtcars df$mpg[c(1, 5, 10)] <- NA df$hp[c(2, 5, 15)] <- NA missing_analysis(df) ## End(Not run)
This function conducts a complete mosaic plot analysis for two categorical variables. It includes filtering by minimum count, chi-square testing (with optional Fisher's exact test), calculation of Cramer's V with effect size interpretation, and generation of a detailed summary table with observed/expected counts and residuals.
mosaic_analysis( data, var1, var2, by = NULL, min_count = 10, fontsize = 8, title = "", var1_label = NULL, var2_label = NULL, show_varnames = FALSE, plot_style = c("flat", "classic"), tile_label = c("count", "percent", "count_percent", "residual", "category", "none"), col_label_side = c("top", "bottom", "both", "none"), row_label_side = c("left", "right", "both", "none"), col_label_angle = 0, row_label_angle = 0, show_legend = TRUE, legend_position = "right", legend_size = 0.7, legend_title = "Std.\nresidual", label_size = 3.5, show_percentages = TRUE, percentage_base = "total", use_fisher = FALSE, by_label = NULL, min_stratum_n = 30, p_adjust = "BH", facet_ncol = NULL, facet_show_n = TRUE, seed = NULL, verbose = TRUE, save_plot = NULL, interpret = FALSE, ... )mosaic_analysis( data, var1, var2, by = NULL, min_count = 10, fontsize = 8, title = "", var1_label = NULL, var2_label = NULL, show_varnames = FALSE, plot_style = c("flat", "classic"), tile_label = c("count", "percent", "count_percent", "residual", "category", "none"), col_label_side = c("top", "bottom", "both", "none"), row_label_side = c("left", "right", "both", "none"), col_label_angle = 0, row_label_angle = 0, show_legend = TRUE, legend_position = "right", legend_size = 0.7, legend_title = "Std.\nresidual", label_size = 3.5, show_percentages = TRUE, percentage_base = "total", use_fisher = FALSE, by_label = NULL, min_stratum_n = 30, p_adjust = "BH", facet_ncol = NULL, facet_show_n = TRUE, seed = NULL, verbose = TRUE, save_plot = NULL, interpret = FALSE, ... )
data |
A data frame containing the variables. |
var1 |
Character. Name of the first categorical variable. |
var2 |
Character. Name of the second categorical variable. |
by |
Character. Optional name of a third categorical variable to
stratify (facet) on. When supplied, the |
min_count |
The minimum number of observations required for a category to be included in the analysis. Defaults to 10. |
fontsize |
The font size for the mosaic plot labels. Defaults to 8. |
title |
The title for the mosaic plot. Defaults to "". |
var1_label |
The label for the first variable in the plot. If NULL, uses the variable name. |
var2_label |
The label for the second variable in the plot. If NULL, uses the variable name. |
show_varnames |
Logical. If TRUE, draws the variable-name titles along the plot axes (e.g. the row and column variable names). Defaults to FALSE because these titles often overprint the category labels, especially when a thin category sits next to them. The category labels and column headers remain visible either way. |
plot_style |
The mosaic plot style: "flat" (a modern flat ggplot2 mosaic shaded by standardized residuals; the default) or "classic" (the vcd shaded mosaic). |
tile_label |
(flat style) What to print inside each tile: "count" (the
default actual counts), "percent" (using |
col_label_side |
(flat style) Placement of the first-variable labels: "top" (default), "bottom", "both", or "none". |
row_label_side |
(flat style) Placement of the second-variable labels: "left" (default), "right", "both", or "none". |
col_label_angle, row_label_angle
|
(flat style) Rotation in degrees for the column and row category labels (0 = horizontal, 90 = vertical). |
show_legend |
Logical. Show the residual colour legend. Defaults to TRUE. |
legend_position |
Legend placement for the flat style: one of "right" (default), "left", "top", "bottom", or "none". |
legend_size |
Numeric multiplier (> 0) scaling the legend key and text in the flat style. Smaller is more compact. Defaults to 0.7. |
legend_title |
Legend title for the flat style. Defaults to "Std.\nresidual". |
label_size |
Tile-label text size for the flat style. Defaults to 3.5. |
show_percentages |
Logical. If TRUE, includes percentages in the summary table. Defaults to TRUE. |
percentage_base |
The base for calculating percentages ("total", "row", or "column"). Defaults to "total". |
use_fisher |
Logical. If TRUE, uses Fisher's exact test instead of chi-square (recommended for small expected cell counts). Defaults to FALSE. |
by_label |
Label for the stratifying variable. If NULL, uses |
min_stratum_n |
Minimum number of observations for a stratum to be fitted. Strata below this, or no longer spanning at least two levels of each variable, are dropped with a warning naming them. Defaults to 30. |
p_adjust |
Multiplicity correction applied to the per-stratum p-values,
passed to |
facet_ncol |
Number of facet columns in a stratified plot. NULL (the default) lets ggplot2 choose. |
facet_show_n |
Logical. Append "(n = ...)" to each panel strip so equal panel widths never imply equal sample sizes. Defaults to TRUE. |
seed |
Optional integer. Seeds the Monte-Carlo Fisher p-value so a fit is reproducible; the caller's RNG stream is restored on exit. Defaults to NULL (no seeding). |
verbose |
Logical. If TRUE, prints results to console. Defaults to TRUE. |
save_plot |
Optional file path to save the mosaic plot. Supports .png, .pdf, .svg. Defaults to NULL (no saving). |
interpret |
Logical. Pass results to AI for automatic interpretation?
Default FALSE. When TRUE, generates clean Methods and Results text using
AI. Includes chi-square/Fisher test results and Cramer's V effect size.
Requires API key setup (see |
... |
Additional arguments passed to |
A list of class "mosaic_analysis" containing:
plot: The mosaic plot object
consolidated_table: Tibble with observed, expected counts and percentages
residuals: Data frame of standardized Pearson residuals
chi_test: Chi-square test results (or Fisher's test if use_fisher=TRUE)
cramers_v: Cramer's V effect size value
cramers_v_interpretation: Effect size interpretation (negligible/small/medium/large)
stats_summary: Tibble summarizing all statistical results
filtered_data: The filtered data used for analysis
original_n: Original sample size before filtering
filtered_n: Sample size after filtering
removed_categories: List of categories removed due to min_count
When by is supplied the object additionally gains class
"mosaic_stratified" and the fields strata_summary (one row per
stratum: n, test, statistic, df, raw and adjusted p, Cramer's V, effect
size, and the number of cells beyond |2|), strata_residuals (one row
per stratum x cell), strata_table, and overall_summary (the
pooled test beside the Cochran-Mantel-Haenszel test of association
conditional on the stratifier). Reach these with
as.data.frame, e.g.
as.data.frame(fit, what = "strata").
# Create example data set.seed(123) example_data <- data.frame( gender = sample(c("Male", "Female"), 200, replace = TRUE), education = sample(c("High School", "Bachelor", "Master", "PhD"), 200, replace = TRUE, prob = c(0.3, 0.4, 0.2, 0.1)) ) # Basic usage with quoted variable names results <- mosaic_analysis(example_data, "gender", "education") # Access results results$cramers_v results$cramers_v_interpretation results$stats_summary # With row percentages and custom labels results <- mosaic_analysis( example_data, "gender", "education", min_count = 5, var1_label = "Gender", var2_label = "Education Level", percentage_base = "row" ) # Using Fisher's exact test for small samples results <- mosaic_analysis( example_data, "gender", "education", use_fisher = TRUE, verbose = FALSE ) # Stratify (facet) on a third variable: one mosaic and one test per region, # with p-values corrected across strata. example_data$region <- sample(c("North", "South"), 200, replace = TRUE) by_region <- mosaic_analysis( example_data, "gender", "education", by = "region", min_count = 5, min_stratum_n = 20, verbose = FALSE ) as.data.frame(by_region, what = "strata") as.data.frame(by_region, what = "overall")# Create example data set.seed(123) example_data <- data.frame( gender = sample(c("Male", "Female"), 200, replace = TRUE), education = sample(c("High School", "Bachelor", "Master", "PhD"), 200, replace = TRUE, prob = c(0.3, 0.4, 0.2, 0.1)) ) # Basic usage with quoted variable names results <- mosaic_analysis(example_data, "gender", "education") # Access results results$cramers_v results$cramers_v_interpretation results$stats_summary # With row percentages and custom labels results <- mosaic_analysis( example_data, "gender", "education", min_count = 5, var1_label = "Gender", var2_label = "Education Level", percentage_base = "row" ) # Using Fisher's exact test for small samples results <- mosaic_analysis( example_data, "gender", "education", use_fisher = TRUE, verbose = FALSE ) # Stratify (facet) on a third variable: one mosaic and one test per region, # with p-values corrected across strata. example_data$region <- sample(c("North", "South"), 200, replace = TRUE) by_region <- mosaic_analysis( example_data, "gender", "education", by = "region", min_count = 5, min_stratum_n = 20, verbose = FALSE ) as.data.frame(by_region, what = "strata") as.data.frame(by_region, what = "overall")
Tests and visualizes normality assumptions for numeric variables using Shapiro-Wilk test, skewness, kurtosis, and Q-Q plots.
normality_check(data, Vars, tests = TRUE, plots = TRUE, digits = 3)normality_check(data, Vars, tests = TRUE, plots = TRUE, digits = 3)
data |
A data frame containing the variables. |
Vars |
Character vector of numeric variable names to check. |
tests |
Logical. Perform normality tests? Default TRUE. |
plots |
Logical. Create Q-Q plots? Default TRUE. |
digits |
Integer. Number of decimal places. Default 3. |
A list containing:
table: A gt table with normality statistics
plots: Q-Q plots (if requested)
results: Data frame with all statistics
## Not run: normality_check(mtcars, Vars = c("mpg", "hp", "wt")) ## End(Not run)## Not run: normality_check(mtcars, Vars = c("mpg", "hp", "wt")) ## End(Not run)
Detects univariate and multivariate outliers using various methods including z-score (2SD, 3SD, etc.), IQR, percentile, or Mahalanobis distance.
outlier_check( data, Vars, method = c("zscore", "iqr", "percentile", "mahalanobis"), threshold = NULL, flag = TRUE, plot = TRUE )outlier_check( data, Vars, method = c("zscore", "iqr", "percentile", "mahalanobis"), threshold = NULL, flag = TRUE, plot = TRUE )
data |
A data frame containing the variables. |
Vars |
Character vector of numeric variable names to check. |
method |
Detection method: "zscore", "iqr", "percentile", or "mahalanobis". |
threshold |
Numeric threshold for outlier detection. For zscore: number of SDs (default 3). Common values: 2, 2.5, 3, 3.29. For iqr: IQR multiplier (default 1.5). Common values: 1.5, 3. For percentile: percentile cutoff (default 0.01 for 1st/99th). Values like 0.05 for 5th/95th. For mahalanobis: chi-sq p-value threshold (default 0.001). |
flag |
Logical. Add outlier flag column to returned data? Default TRUE. |
plot |
Logical. Create outlier visualization? Default TRUE. |
A list containing:
summary: gt table with outlier summary
data: Data frame with outlier flags (if flag = TRUE)
outlier_indices: Row indices of outliers
plot: Visualization (if requested)
## Not run: # Z-score with 3 SD threshold outlier_check(mtcars, Vars = c("mpg", "hp"), method = "zscore", threshold = 3) # Z-score with 2 SD threshold (more conservative) outlier_check(mtcars, Vars = c("mpg", "hp"), method = "zscore", threshold = 2) # IQR method outlier_check(mtcars, Vars = c("mpg", "hp"), method = "iqr", threshold = 1.5) # Percentile method (1st and 99th percentile) outlier_check(mtcars, Vars = c("mpg", "hp"), method = "percentile", threshold = 0.01) # Percentile method (5th and 95th percentile) outlier_check(mtcars, Vars = c("mpg", "hp"), method = "percentile", threshold = 0.05) # Mahalanobis distance (multivariate) outlier_check(mtcars, Vars = c("mpg", "hp", "wt"), method = "mahalanobis") ## End(Not run)## Not run: # Z-score with 3 SD threshold outlier_check(mtcars, Vars = c("mpg", "hp"), method = "zscore", threshold = 3) # Z-score with 2 SD threshold (more conservative) outlier_check(mtcars, Vars = c("mpg", "hp"), method = "zscore", threshold = 2) # IQR method outlier_check(mtcars, Vars = c("mpg", "hp"), method = "iqr", threshold = 1.5) # Percentile method (1st and 99th percentile) outlier_check(mtcars, Vars = c("mpg", "hp"), method = "percentile", threshold = 0.01) # Percentile method (5th and 95th percentile) outlier_check(mtcars, Vars = c("mpg", "hp"), method = "percentile", threshold = 0.05) # Mahalanobis distance (multivariate) outlier_check(mtcars, Vars = c("mpg", "hp", "wt"), method = "mahalanobis") ## End(Not run)
Pipes any R output (test results, model summaries, tables) to an AI model for scientific interpretation. Perfect for getting publication-ready interpretations of statistical results.
pass( x, prompt = NULL, append_prompt = NULL, action = c("write", "interpret", "explain", "summarize", "critique", "suggest"), style = c("scientific", "simple", "detailed", "brief"), output = c("text", "markdown", "md", "latex", "html"), provider = c("openai", "anthropic", "gemini", "openrouter"), model = NULL, base_url = NULL, api_key = NULL, context = NULL, system_message = NULL, auto_local = TRUE, copy = FALSE, quiet = FALSE )pass( x, prompt = NULL, append_prompt = NULL, action = c("write", "interpret", "explain", "summarize", "critique", "suggest"), style = c("scientific", "simple", "detailed", "brief"), output = c("text", "markdown", "md", "latex", "html"), provider = c("openai", "anthropic", "gemini", "openrouter"), model = NULL, base_url = NULL, api_key = NULL, context = NULL, system_message = NULL, auto_local = TRUE, copy = FALSE, quiet = FALSE )
x |
Any R object to interpret (test result, model, data frame, etc.) |
prompt |
Custom prompt to use. If NULL, builds from action and style. Note: This REPLACES the default prompt entirely. |
append_prompt |
Additional instructions to ADD to the default prompt. Unlike 'prompt', this appends to (not replaces) the auto-generated prompt. |
action |
What to do with the output:
|
style |
Interpretation style:
|
output |
Output format:
|
provider |
AI provider: '"openai"' (default), '"anthropic"', '"gemini"', or '"openrouter"'. |
model |
Model to use. Defaults: '"gpt-4.1-nano"' (OpenAI), '"claude-sonnet-4-20250514"' (Anthropic), '"gemini-2.5-flash"' (Gemini), '"anthropic/claude-sonnet-4"' (OpenRouter). |
base_url |
Custom API base URL for OpenAI-compatible servers (e.g., LM Studio, Ollama, vLLM). Example: '"http://127.0.0.1:1234"' for LM Studio. When set, uses OpenAI-compatible format regardless of provider setting. |
api_key |
API key. If NULL, checks environment variables ('OPENAI_API_KEY', 'ANTHROPIC_API_KEY', 'GEMINI_API_KEY', or 'OPENROUTER_API_KEY'), then prompts interactively. For local servers like LM Studio, use 'api_key = "none"' or any string. |
context |
Optional context about your study (e.g., "This is a study on student learning outcomes with N=500 participants") |
system_message |
Optional custom instructions for the AI (e.g., "Focus on clinical implications", "Be more concise", "Emphasize effect sizes") |
auto_local |
Logical. Automatically detect and use local AI servers (LM Studio on port 1234, Ollama on port 11434)? Default: TRUE. Set to FALSE to force using cloud providers. |
copy |
Logical. Copy result to clipboard? Default: FALSE |
quiet |
Logical. Suppress messages? Default: FALSE |
On first use, you'll be prompted to enter your API key. The key is stored in your R environment for the session. To persist it, add to your .Renviron: “' ANTHROPIC_API_KEY=your-key-here # or OPENAI_API_KEY=your-key-here “'
Character string with the AI interpretation (invisibly). Also prints the interpretation.
## Not run: # Basic usage - pipe test results t.test(mpg ~ am, data = mtcars) |> pass() # With context cor.test(mtcars$mpg, mtcars$hp) |> pass(context = "Studying fuel efficiency in 1974 automobiles") # Different actions lm(mpg ~ wt + hp, data = mtcars) |> summary() |> pass(action = "write") chisq.test(mtcars$cyl, mtcars$am) |> pass(action = "explain", style = "simple") # Get LaTeX output for paper aov(mpg ~ factor(cyl), data = mtcars) |> summary() |> pass(action = "write", output = "latex") # Critique an analysis lm(mpg ~ ., data = mtcars) |> summary() |> pass(action = "critique") # Custom prompt (REPLACES default - specific request to the AI) my_results |> pass(prompt = "Focus only on the interaction effects") # Add to default prompt (keeps "write methods/results" + your addition) my_results |> pass(append_prompt = "Also mention limitations of the sample size") my_results |> pass(action = "write", append_prompt = "Include a brief discussion section") # Custom context (about your study) t.test(score ~ group, data = mydata) |> pass(context = "RCT comparing drug vs placebo, N=200 patients with diabetes") # Custom system message (instructions for the AI) my_results |> pass(system_message = "Focus on clinical implications and effect sizes") # Combine all customizations lm(outcome ~ treatment * age, data = mydata) |> summary() |> pass( action = "write", context = "Phase 3 clinical trial for hypertension medication", system_message = "Emphasize clinical significance over statistical significance", prompt = "Pay special attention to the treatment-age interaction" ) ## End(Not run)## Not run: # Basic usage - pipe test results t.test(mpg ~ am, data = mtcars) |> pass() # With context cor.test(mtcars$mpg, mtcars$hp) |> pass(context = "Studying fuel efficiency in 1974 automobiles") # Different actions lm(mpg ~ wt + hp, data = mtcars) |> summary() |> pass(action = "write") chisq.test(mtcars$cyl, mtcars$am) |> pass(action = "explain", style = "simple") # Get LaTeX output for paper aov(mpg ~ factor(cyl), data = mtcars) |> summary() |> pass(action = "write", output = "latex") # Critique an analysis lm(mpg ~ ., data = mtcars) |> summary() |> pass(action = "critique") # Custom prompt (REPLACES default - specific request to the AI) my_results |> pass(prompt = "Focus only on the interaction effects") # Add to default prompt (keeps "write methods/results" + your addition) my_results |> pass(append_prompt = "Also mention limitations of the sample size") my_results |> pass(action = "write", append_prompt = "Include a brief discussion section") # Custom context (about your study) t.test(score ~ group, data = mydata) |> pass(context = "RCT comparing drug vs placebo, N=200 patients with diabetes") # Custom system message (instructions for the AI) my_results |> pass(system_message = "Focus on clinical implications and effect sizes") # Combine all customizations lm(outcome ~ treatment * age, data = mydata) |> summary() |> pass( action = "write", context = "Phase 3 clinical trial for hypertension medication", system_message = "Emphasize clinical significance over statistical significance", prompt = "Pay special attention to the treatment-age interaction" ) ## End(Not run)
Builds figures of a clustering() result with latents, as ggplot
objects. type takes any mix of plot types and groups:
"clusters": "profiles", "bars", "heatmap", "raincloud",
"parallel", "pairs", "sizes".
"diagnostics": "entropy", "posteriors", "avepp".
"selection": "enumeration" (information criteria across the
candidates) and "tree" (how profiles split as more are added); both
need more than one candidate.
"all": every type above.
plot_clustering(results, type = "clusters", ...)plot_clustering(results, type = "clusters", ...)
results |
A |
type |
Plot types and/or groups; see |
... |
Passed to the latents plot method of the selected fit,
e.g. |
One type: a ggplot object. Several: a saqr_plots list of ggplot
objects named by type, which draws every one when printed. Print, save
with ggplot2::ggsave(), or restyle with + ggplot2::theme().
Raises saqrmisc_bad_input when results is not a clustering() result
and saqrmisc_bad_type for an unknown type. A selection view that needs
more candidates than were fitted is skipped with a message.
clustering(), clustering_plot_types()
set.seed(1) vars <- c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width") fit <- clustering(iris, vars, n_profiles = 2:4, models = "EEE") plot_clustering(fit, type = "profiles") plot_clustering(fit, type = "diagnostics") plot_clustering(fit, type = c("pairs", "tree"))set.seed(1) vars <- c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width") fit <- clustering(iris, vars, n_profiles = 2:4, models = "EEE") plot_clustering(fit, type = "profiles") plot_clustering(fit, type = "diagnostics") plot_clustering(fit, type = c("pairs", "tree"))
Re-renders the mosaic plot from a fitted mosaic_analysis object using
the stored contingency table and residuals, so styling can be changed without
re-running the statistical test. Any styling argument accepted by
mosaic_analysis (e.g. plot_style, tile_label,
col_label_side, legend_size) can be overridden via ...;
unspecified arguments keep the values from the original call.
## S3 method for class 'mosaic_analysis' plot(x, ...)## S3 method for class 'mosaic_analysis' plot(x, ...)
x |
A |
... |
Styling overrides (see |
Invisibly, the plot object (a ggplot for the flat style). Called for its side effect of drawing the plot.
set.seed(1) d <- data.frame( a = sample(c("X", "Y", "Z"), 200, replace = TRUE), b = sample(c("P", "Q"), 200, replace = TRUE) ) res <- mosaic_analysis(d, "a", "b", min_count = 5, verbose = FALSE) plot(res, tile_label = "percent", legend_size = 0.4) plot(res, plot_style = "classic")set.seed(1) d <- data.frame( a = sample(c("X", "Y", "Z"), 200, replace = TRUE), b = sample(c("P", "Q"), 200, replace = TRUE) ) res <- mosaic_analysis(d, "a", "b", min_count = 5, verbose = FALSE) plot(res, tile_label = "percent", legend_size = 0.4) plot(res, plot_style = "classic")
Plot Method for Clustering Results
## S3 method for class 'saqr_clustering' plot(x, type = "clusters", ...)## S3 method for class 'saqr_clustering' plot(x, type = "clusters", ...)
x |
A 'saqr_clustering' object from [clustering()]. |
type |
Plot types and/or groups; see [plot_clustering()]. |
... |
Passed to [plot_clustering()]. |
As [plot_clustering()]: a ggplot object, or a 'saqr_plots' list.
Print method for grouped_network_analysis objects
## S3 method for class 'grouped_network_analysis' print(x, ...)## S3 method for class 'grouped_network_analysis' print(x, ...)
x |
A grouped_network_analysis object |
... |
Additional arguments (ignored) |
Print method for html tables
## S3 method for class 'html_table' print(x, ...)## S3 method for class 'html_table' print(x, ...)
x |
An html_table object |
... |
Additional arguments (ignored) |
Print method for latex tables
## S3 method for class 'latex_table' print(x, ...)## S3 method for class 'latex_table' print(x, ...)
x |
A latex_table object |
... |
Additional arguments (ignored) |
Print method for markdown tables
## S3 method for class 'markdown_table' print(x, ...)## S3 method for class 'markdown_table' print(x, ...)
x |
A markdown_table object |
... |
Additional arguments (ignored) |
Print method for mosaic_analysis objects
## S3 method for class 'mosaic_analysis' print(x, ...)## S3 method for class 'mosaic_analysis' print(x, ...)
x |
A mosaic_analysis object |
... |
Additional arguments (ignored) |
Print method for stratified mosaic_analysis objects
## S3 method for class 'mosaic_stratified' print(x, ...)## S3 method for class 'mosaic_stratified' print(x, ...)
x |
A |
... |
Additional arguments (ignored). |
Invisibly, x. Called for its side effect of printing.
Print method for network_analysis objects
## S3 method for class 'network_analysis' print(x, ...)## S3 method for class 'network_analysis' print(x, ...)
x |
A network_analysis object |
... |
Additional arguments (ignored) |
Print a Clustering Result
## S3 method for class 'saqr_clustering' print(x, ...)## S3 method for class 'saqr_clustering' print(x, ...)
x |
A 'saqr_clustering' object from [clustering()]. |
... |
Ignored. |
'x', invisibly.
Print Several Clustering Plots
## S3 method for class 'saqr_plots' print(x, ...)## S3 method for class 'saqr_plots' print(x, ...)
x |
A 'saqr_plots' list from [plot_clustering()]. |
... |
Ignored. |
'x', invisibly. Called for the side effect of drawing each plot.
Print method for saqr_result
## S3 method for class 'saqr_result' print(x, ...)## S3 method for class 'saqr_result' print(x, ...)
x |
A saqr_result object |
... |
Additional arguments (ignored) |
Imputes missing values using various methods including mean, median, mode, or custom values.
replace_missing( data, Vars, method = c("mean", "median", "mode", "zero", "min", "max", "value"), value = NULL, group_by = NULL, suffix = NULL )replace_missing( data, Vars, method = c("mean", "median", "mode", "zero", "min", "max", "value"), value = NULL, group_by = NULL, suffix = NULL )
data |
A data frame. |
Vars |
Character vector of variable names to impute. |
method |
Imputation method: "mean", "median", "mode", "zero", "min", "max", or "value". |
value |
Custom value to use when method = "value". |
group_by |
Character. Name of grouping variable for group-wise imputation. Optional. |
suffix |
Character. Suffix for new columns. If NULL (default), replaces in place. |
Data frame with imputed values.
## Not run: df <- mtcars df$mpg[c(1, 5, 10)] <- NA # Replace with mean df_imputed <- replace_missing(df, Vars = "mpg", method = "mean") # Replace with median, create new column df_imputed <- replace_missing(df, Vars = "mpg", method = "median", suffix = "_imp") # Group-wise mean imputation df_imputed <- replace_missing(df, Vars = "mpg", method = "mean", group_by = "cyl") ## End(Not run)## Not run: df <- mtcars df$mpg[c(1, 5, 10)] <- NA # Replace with mean df_imputed <- replace_missing(df, Vars = "mpg", method = "mean") # Replace with median, create new column df_imputed <- replace_missing(df, Vars = "mpg", method = "median", suffix = "_imp") # Group-wise mean imputation df_imputed <- replace_missing(df, Vars = "mpg", method = "mean", group_by = "cyl") ## End(Not run)
Replaces detected outliers with specified values such as NA, mean, median, or winsorized values. Supports multiple detection methods.
replace_outliers( data, Vars, detect = c("zscore", "iqr", "percentile"), threshold = NULL, replace_with = c("NA", "mean", "median", "winsorize", "boundary"), suffix = NULL )replace_outliers( data, Vars, detect = c("zscore", "iqr", "percentile"), threshold = NULL, replace_with = c("NA", "mean", "median", "winsorize", "boundary"), suffix = NULL )
data |
A data frame. |
Vars |
Character vector of numeric variable names to process. |
detect |
Detection method: "zscore", "iqr", or "percentile". |
threshold |
Numeric threshold for detection. For zscore: number of SDs (default 3). Use 2 for 2SD, 2.5 for 2.5SD, etc. For iqr: IQR multiplier (default 1.5). For percentile: percentile cutoff (default 0.01 for 1st/99th). |
replace_with |
Replacement method: "NA", "mean", "median", "winsorize", or "boundary". |
suffix |
Character. Suffix for new columns. If NULL (default), replaces in place. |
Detection methods:
"zscore": Values beyond threshold SDs from mean. Common thresholds: 2, 2.5, 3, 3.29
"iqr": Values beyond Q1/Q3 +/- threshold*IQR. Common thresholds: 1.5, 3
"percentile": Values below or above percentile cutoffs. E.g., 0.01 = 1st/99th, 0.05 = 5th/95th
Replacement methods:
"NA": Set outliers to NA
"mean": Replace with mean of non-outliers
"median": Replace with median of non-outliers
"winsorize": Cap at threshold boundary
"boundary": Replace with nearest non-outlier value
Data frame with outliers replaced.
## Not run: df <- mtcars # Replace outliers beyond 2 SD with NA df_clean <- replace_outliers(df, Vars = "hp", detect = "zscore", threshold = 2, replace_with = "NA") # Winsorize at 3 SD df_clean <- replace_outliers(df, Vars = "hp", detect = "zscore", threshold = 3, replace_with = "winsorize") # Replace outliers at 5th/95th percentile with median df_clean <- replace_outliers(df, Vars = "hp", detect = "percentile", threshold = 0.05, replace_with = "median") # IQR-based winsorization df_clean <- replace_outliers(df, Vars = c("mpg", "hp"), detect = "iqr", replace_with = "winsorize") ## End(Not run)## Not run: df <- mtcars # Replace outliers beyond 2 SD with NA df_clean <- replace_outliers(df, Vars = "hp", detect = "zscore", threshold = 2, replace_with = "NA") # Winsorize at 3 SD df_clean <- replace_outliers(df, Vars = "hp", detect = "zscore", threshold = 3, replace_with = "winsorize") # Replace outliers at 5th/95th percentile with median df_clean <- replace_outliers(df, Vars = "hp", detect = "percentile", threshold = 0.05, replace_with = "median") # IQR-based winsorization df_clean <- replace_outliers(df, Vars = c("mpg", "hp"), detect = "iqr", replace_with = "winsorize") ## End(Not run)
Reverse codes numeric variables, commonly used for Likert scales where some items are negatively worded. Uses the formula: reversed = (max + min) - original.
reverse_code(data, Vars, min = NULL, max = NULL, suffix = "_r")reverse_code(data, Vars, min = NULL, max = NULL, suffix = "_r")
data |
A data frame. |
Vars |
Character vector of variable names to reverse code. |
min |
Numeric. Minimum value of the scale. If NULL (default), detected from data. |
max |
Numeric. Maximum value of the scale. If NULL (default), detected from data. |
suffix |
Character. Suffix for new column names. Default "_r". |
The reverse coding formula is: reversed = (max + min) - original
For a 1-5 Likert scale:
1 becomes 5
2 becomes 4
3 stays 3
4 becomes 2
5 becomes 1
If min/max are not specified, they are detected from the data. For Likert scales, it's recommended to explicitly specify min and max to ensure correct reversal even if extreme values are not present in the data.
Data frame with reverse coded variables added.
## Not run: # Create sample Likert data df <- data.frame( item1 = c(1, 2, 3, 4, 5), item2 = c(5, 4, 3, 2, 1), # reverse-worded item3 = c(2, 3, 4, 3, 2) ) # Reverse code with automatic detection df <- reverse_code(df, Vars = "item2") # Reverse code with explicit scale (1-5 Likert) df <- reverse_code(df, Vars = "item2", min = 1, max = 5) # Reverse code multiple items df <- reverse_code(df, Vars = c("item2", "item3"), min = 1, max = 5) # 0-10 scale df <- reverse_code(df, Vars = "item2", min = 0, max = 10) ## End(Not run)## Not run: # Create sample Likert data df <- data.frame( item1 = c(1, 2, 3, 4, 5), item2 = c(5, 4, 3, 2, 1), # reverse-worded item3 = c(2, 3, 4, 3, 2) ) # Reverse code with automatic detection df <- reverse_code(df, Vars = "item2") # Reverse code with explicit scale (1-5 Likert) df <- reverse_code(df, Vars = "item2", min = 1, max = 5) # Reverse code multiple items df <- reverse_code(df, Vars = c("item2", "item3"), min = 1, max = 5) # 0-10 scale df <- reverse_code(df, Vars = "item2", min = 0, max = 10) ## End(Not run)
Vectorized reverse coding for use with dplyr mutate and across.
reverse_code_vec(x, min = NULL, max = NULL, na.rm = TRUE)reverse_code_vec(x, min = NULL, max = NULL, na.rm = TRUE)
x |
Numeric vector to reverse code. |
min |
Numeric. Minimum value of the scale. If NULL (default), detected from data. |
max |
Numeric. Maximum value of the scale. If NULL (default), detected from data. |
na.rm |
Logical. Remove NA values when detecting min/max? Default TRUE. |
The reverse coding formula is: reversed = (max + min) - original
For Likert scales, always specify min and max explicitly to ensure correct reversal even when extreme values are not present in the data.
Reverse coded numeric vector.
## Not run: library(dplyr) df <- data.frame( item1 = c(1, 2, 3, 4, 5), item2 = c(5, 4, 3, 2, 1), item3 = c(2, 3, 4, 3, 2) ) # Reverse single variable (auto-detect scale) df %>% mutate(item2_r = reverse_code_vec(item2)) # Reverse with explicit 1-5 scale df %>% mutate(item2_r = reverse_code_vec(item2, min = 1, max = 5)) # Reverse multiple variables df %>% mutate(across(c(item2, item3), ~reverse_code_vec(.x, min = 1, max = 5), .names = "{.col}_r")) # 0-10 scale df %>% mutate(item2_r = reverse_code_vec(item2, min = 0, max = 10)) # 1-7 Likert scale df %>% mutate(item2_r = reverse_code_vec(item2, min = 1, max = 7)) ## End(Not run)## Not run: library(dplyr) df <- data.frame( item1 = c(1, 2, 3, 4, 5), item2 = c(5, 4, 3, 2, 1), item3 = c(2, 3, 4, 3, 2) ) # Reverse single variable (auto-detect scale) df %>% mutate(item2_r = reverse_code_vec(item2)) # Reverse with explicit 1-5 scale df %>% mutate(item2_r = reverse_code_vec(item2, min = 1, max = 5)) # Reverse multiple variables df %>% mutate(across(c(item2, item3), ~reverse_code_vec(.x, min = 1, max = 5), .names = "{.col}_r")) # 0-10 scale df %>% mutate(item2_r = reverse_code_vec(item2, min = 0, max = 10)) # 1-7 Likert scale df %>% mutate(item2_r = reverse_code_vec(item2, min = 1, max = 7)) ## End(Not run)
Creates a standardized result object for Saqrmisc functions that includes both the original data and a clean markdown representation for AI interpretation.
saqr_result(data = NULL, table = NULL, type = "analysis", markdown = NULL, ...)saqr_result(data = NULL, table = NULL, type = "analysis", markdown = NULL, ...)
data |
The main data (data frame or tibble with results) |
table |
Optional gt table or formatted table |
type |
Character describing the analysis type (e.g., "group_comparison", "correlation", "descriptive") |
markdown |
Optional pre-built markdown string. If NULL, auto-generated from data. |
... |
Additional components to include in the result |
A list with class "saqr_result" containing data, table, markdown, and other components
Scales numeric variables by dividing by standard deviation or rescaling to a specified range. Supports group-wise scaling.
scale_vars( data, Vars, method = c("sd", "range"), range = c(0, 1), suffix = "_s", group_by = NULL )scale_vars( data, Vars, method = c("sd", "range"), range = c(0, 1), suffix = "_s", group_by = NULL )
data |
A data frame. |
Vars |
Character vector of numeric variable names to scale. |
method |
Scaling method: "sd" (divide by SD) or "range" (min-max scaling). |
range |
Numeric vector of length 2 specifying target range for "range" method. Default c(0, 1). Use c(1, 10) for 1-10 scaling. |
suffix |
Character. Suffix for new column names. Default "_s". |
group_by |
Character. Name of grouping variable for group-wise scaling. Optional. |
Data frame with scaled variables added.
## Not run: # Scale by SD df <- scale_vars(mtcars, Vars = c("mpg", "hp"), method = "sd") # Min-max scaling (0-1) df <- scale_vars(mtcars, Vars = "mpg", method = "range") # Scale to 1-10 range df <- scale_vars(mtcars, Vars = "mpg", method = "range", range = c(1, 10)) # Group-wise scaling df <- scale_vars(mtcars, Vars = "mpg", method = "sd", group_by = "cyl") ## End(Not run)## Not run: # Scale by SD df <- scale_vars(mtcars, Vars = c("mpg", "hp"), method = "sd") # Min-max scaling (0-1) df <- scale_vars(mtcars, Vars = "mpg", method = "range") # Scale to 1-10 range df <- scale_vars(mtcars, Vars = "mpg", method = "range", range = c(1, 10)) # Group-wise scaling df <- scale_vars(mtcars, Vars = "mpg", method = "sd", group_by = "cyl") ## End(Not run)
Vectorized scaling function for use with dplyr mutate and across. For group-wise scaling, use dplyr::group_by() before mutate().
scale_vec(x, method = c("sd", "range"), range = c(0, 1), na.rm = TRUE)scale_vec(x, method = c("sd", "range"), range = c(0, 1), na.rm = TRUE)
x |
Numeric vector to scale. |
method |
Scaling method: "sd" or "range". |
range |
Target range for "range" method. Default c(0, 1). |
na.rm |
Logical. Remove NA values? Default TRUE. |
Scaled numeric vector.
## Not run: library(dplyr) # Scale by SD mtcars %>% mutate(mpg_s = scale_vec(mpg, method = "sd")) # Scale to 1-10 mtcars %>% mutate(mpg_s = scale_vec(mpg, method = "range", range = c(1, 10))) # Multiple variables to 0-100 mtcars %>% mutate(across(c(mpg, hp), ~scale_vec(.x, method = "range", range = c(0, 100)))) # Group-wise scaling mtcars %>% group_by(cyl) %>% mutate(mpg_s = scale_vec(mpg, method = "sd")) ## End(Not run)## Not run: library(dplyr) # Scale by SD mtcars %>% mutate(mpg_s = scale_vec(mpg, method = "sd")) # Scale to 1-10 mtcars %>% mutate(mpg_s = scale_vec(mpg, method = "range", range = c(1, 10))) # Multiple variables to 0-100 mtcars %>% mutate(across(c(mpg, hp), ~scale_vec(.x, method = "range", range = c(0, 100)))) # Group-wise scaling mtcars %>% group_by(cyl) %>% mutate(mpg_s = scale_vec(mpg, method = "sd")) ## End(Not run)
Set your API key and optional default settings for the current R session. Settings are stored as R options and used as defaults by 'pass()'.
set_api_key( key, provider = c("openai", "anthropic", "gemini", "openrouter"), model = NULL, ... )set_api_key( key, provider = c("openai", "anthropic", "gemini", "openrouter"), model = NULL, ... )
key |
Your API key |
provider |
Provider name: "openai" (default), "anthropic", "gemini", or "openrouter" |
model |
Optional. Default model to use for this provider. |
... |
Additional options to store (e.g., 'base_url', 'timeout'). |
Invisibly returns TRUE.
## Not run: # Just set the key set_api_key("sk-...", "openai") # Set key and default model set_api_key("sk-...", "openai", model = "gpt-4o") # Set key with custom base URL (for Azure OpenAI, etc.) set_api_key("sk-...", "openai", model = "gpt-4", base_url = "https://my-azure.openai.azure.com") ## End(Not run)## Not run: # Just set the key set_api_key("sk-...", "openai") # Set key and default model set_api_key("sk-...", "openai", model = "gpt-4o") # Set key with custom base URL (for Azure OpenAI, etc.) set_api_key("sk-...", "openai", model = "gpt-4", base_url = "https://my-azure.openai.azure.com") ## End(Not run)
Convenience alias for 'set_api_key(key, "anthropic", ...)'.
set_claude_key(key, model = NULL, ...)set_claude_key(key, model = NULL, ...)
key |
Your Anthropic API key |
model |
Optional. Default model (e.g., "claude-sonnet-4-20250514"). |
... |
Additional options. |
## Not run: set_claude_key("sk-ant-...") set_claude_key("sk-ant-...", model = "claude-sonnet-4-20250514") ## End(Not run)## Not run: set_claude_key("sk-ant-...") set_claude_key("sk-ant-...", model = "claude-sonnet-4-20250514") ## End(Not run)
Convenience alias for 'set_api_key(key, "gemini", ...)'.
set_gemini_key(key, model = NULL, ...)set_gemini_key(key, model = NULL, ...)
key |
Your Gemini API key |
model |
Optional. Default model (e.g., "gemini-2.5-flash"). |
... |
Additional options. |
## Not run: set_gemini_key("AIza...") set_gemini_key("AIza...", model = "gemini-2.5-pro") ## End(Not run)## Not run: set_gemini_key("AIza...") set_gemini_key("AIza...", model = "gemini-2.5-pro") ## End(Not run)
Convenience alias for 'set_api_key(key, "openai", ...)'.
set_openai_key(key, model = NULL, ...)set_openai_key(key, model = NULL, ...)
key |
Your OpenAI API key |
model |
Optional. Default model (e.g., "gpt-4o", "gpt-4.1-nano"). |
... |
Additional options (e.g., 'base_url' for Azure OpenAI). |
## Not run: set_openai_key("sk-...") set_openai_key("sk-...", model = "gpt-4o") set_openai_key("sk-...", model = "gpt-4", base_url = "https://my-azure.openai.azure.com") ## End(Not run)## Not run: set_openai_key("sk-...") set_openai_key("sk-...", model = "gpt-4o") set_openai_key("sk-...", model = "gpt-4", base_url = "https://my-azure.openai.azure.com") ## End(Not run)
Convenience alias for 'set_api_key(key, "openrouter", ...)'.
set_openrouter_key(key, model = NULL, ...)set_openrouter_key(key, model = NULL, ...)
key |
Your OpenRouter API key |
model |
Optional. Default model (e.g., "anthropic/claude-sonnet-4", "openai/gpt-4o"). |
... |
Additional options. |
## Not run: set_openrouter_key("sk-or-...") set_openrouter_key("sk-or-...", model = "openai/gpt-4o") ## End(Not run)## Not run: set_openrouter_key("sk-or-...") set_openrouter_key("sk-or-...", model = "openai/gpt-4o") ## End(Not run)
Standardizes numeric variables to z-scores (mean = 0, SD = 1). Supports group-wise standardization for multilevel/nested data.
standardize(data, Vars, suffix = "_z", group_by = NULL)standardize(data, Vars, suffix = "_z", group_by = NULL)
data |
A data frame. |
Vars |
Character vector of numeric variable names to standardize. |
suffix |
Character. Suffix for new column names. Default "_z". |
group_by |
Character. Name of grouping variable for group-wise standardization. Optional. |
Data frame with standardized variables added.
## Not run: # Simple standardization df <- standardize(mtcars, Vars = c("mpg", "hp")) # Group-wise standardization df <- standardize(mtcars, Vars = "mpg", group_by = "cyl") ## End(Not run)## Not run: # Simple standardization df <- standardize(mtcars, Vars = c("mpg", "hp")) # Group-wise standardization df <- standardize(mtcars, Vars = "mpg", group_by = "cyl") ## End(Not run)
Vectorized standardization function for use with dplyr mutate and across. For group-wise standardization, use dplyr::group_by() before mutate().
standardize_vec(x, na.rm = TRUE)standardize_vec(x, na.rm = TRUE)
x |
Numeric vector to standardize. |
na.rm |
Logical. Remove NA values? Default TRUE. |
Standardized numeric vector (mean = 0, SD = 1).
## Not run: library(dplyr) # Single variable mtcars %>% mutate(mpg_z = standardize_vec(mpg)) # Multiple variables mtcars %>% mutate(across(c(mpg, hp, wt), standardize_vec, .names = "{.col}_z")) # Group-wise standardization mtcars %>% group_by(cyl) %>% mutate(mpg_z = standardize_vec(mpg)) ## End(Not run)## Not run: library(dplyr) # Single variable mtcars %>% mutate(mpg_z = standardize_vec(mpg)) # Multiple variables mtcars %>% mutate(across(c(mpg, hp, wt), standardize_vec, .names = "{.col}_z")) # Group-wise standardization mtcars %>% group_by(cyl) %>% mutate(mpg_z = standardize_vec(mpg)) ## End(Not run)
Summary method for mosaic_analysis objects
## S3 method for class 'mosaic_analysis' summary(object, ...)## S3 method for class 'mosaic_analysis' summary(object, ...)
object |
A mosaic_analysis object |
... |
Additional arguments (ignored) |
Summary method for stratified mosaic_analysis objects
## S3 method for class 'mosaic_stratified' summary(object, ...)## S3 method for class 'mosaic_stratified' summary(object, ...)
object |
A |
... |
Additional arguments (ignored). |
Invisibly, the per-stratum summary data.frame.
Summary method for network_analysis objects
## S3 method for class 'network_analysis' summary(object, ...)## S3 method for class 'network_analysis' summary(object, ...)
object |
A network_analysis object |
... |
Additional arguments (ignored) |
Compare the Candidate Models of a Clustering Result
## S3 method for class 'saqr_clustering' summary(object, ...)## S3 method for class 'saqr_clustering' summary(object, ...)
object |
A 'saqr_clustering' object from [clustering()]. |
... |
Ignored. |
A data.frame with one row per candidate (profiles x covariance model): 'n_profiles', 'model', 'log_likelihood', 'n_parameters', 'aic', 'bic', 'icl', 'entropy' (relative), 'converged', 'boundary', 'delta_bic' (distance from the selected model) and 'selected'.
Extracts the underlying data frame from various table objects including gt tables, kable objects, and matrices.
to_dataframe(x, digits = NULL)to_dataframe(x, digits = NULL)
x |
A table object (gt, kable, matrix, or data frame). |
digits |
Number of decimal places for formatting numeric columns. Set to NULL to skip formatting. Default NULL. |
A data frame.
## Not run: # Extract data from a gt table library(gt) gt_table <- gt(mtcars[1:5, 1:3]) df <- to_dataframe(gt_table) # Works with matrices too mat <- matrix(1:6, nrow = 2) to_dataframe(mat) ## End(Not run)## Not run: # Extract data from a gt table library(gt) gt_table <- gt(mtcars[1:5, 1:3]) df <- to_dataframe(gt_table) # Works with matrices too mat <- matrix(1:6, nrow = 2) to_dataframe(mat) ## End(Not run)
Converts a data frame or matrix to a gt table object for publication-ready output. Provides a consistent interface matching other to_* functions.
to_gt( x, title = NULL, subtitle = NULL, digits = 2, rowname_col = NULL, theme = c("default", "fancy", "minimal", "dark", "none") )to_gt( x, title = NULL, subtitle = NULL, digits = 2, rowname_col = NULL, theme = c("default", "fancy", "minimal", "dark", "none") )
x |
A data frame or matrix to convert. |
title |
Optional title for the table. |
subtitle |
Optional subtitle for the table. |
digits |
Number of decimal places for numeric columns. Default 2. |
rowname_col |
Optional column name to use as row names. |
theme |
Character. Visual theme: "default" (clean scientific style), "fancy" (blue headers), "minimal" (simple borders), "dark" (dark mode), or "none" (no styling). Default "default". |
A gt table object.
## Not run: # Convert a data frame to gt df <- data.frame( Variable = c("Age", "Score"), Mean = c(35.2, 78.5), SD = c(10.1, 12.3) ) to_gt(df) to_gt(df, title = "Descriptive Statistics", theme = "fancy") # With row names to_gt(mtcars[1:5, 1:3], rowname_col = NULL) ## End(Not run)## Not run: # Convert a data frame to gt df <- data.frame( Variable = c("Age", "Score"), Mean = c(35.2, 78.5), SD = c(10.1, 12.3) ) to_gt(df) to_gt(df, title = "Descriptive Statistics", theme = "fancy") # With row names to_gt(mtcars[1:5, 1:3], rowname_col = NULL) ## End(Not run)
Converts a data frame or gt table to HTML table format. Works with any tabular data structure.
to_html( x, title = NULL, digits = 2, class = "table", id = NULL, border = 1, style = NULL, header_style = "font-weight: bold;", stripe = FALSE )to_html( x, title = NULL, digits = 2, class = "table", id = NULL, border = 1, style = NULL, header_style = "font-weight: bold;", stripe = FALSE )
x |
A data frame, matrix, or gt table to convert. |
title |
Optional title (added as caption). |
digits |
Number of decimal places for numeric columns. Default 2. |
class |
CSS class(es) for the table element. Default "table". |
id |
Optional HTML id attribute for the table. |
border |
Table border width. Default 1. |
style |
Additional inline CSS style for the table. |
header_style |
CSS style for header cells. Default bold. |
stripe |
Logical. Add striped rows? Default FALSE. |
A character string containing the HTML code with class "html_table" for proper printing.
## Not run: # Convert a data frame to HTML df <- data.frame( Name = c("Alice", "Bob"), Score = c(85, 92) ) to_html(df) to_html(df, title = "Scores", class = "table table-striped") ## End(Not run)## Not run: # Convert a data frame to HTML df <- data.frame( Name = c("Alice", "Bob"), Score = c(85, 92) ) to_html(df) to_html(df, title = "Scores", class = "table table-striped") ## End(Not run)
Converts a data frame or gt table to knitr::kable format for use in R Markdown documents.
to_kable( x, format = c("pipe", "markdown", "html", "latex", "rst"), digits = 2, caption = NULL, col.names = NULL, row.names = FALSE, align = NULL, ... )to_kable( x, format = c("pipe", "markdown", "html", "latex", "rst"), digits = 2, caption = NULL, col.names = NULL, row.names = FALSE, align = NULL, ... )
x |
A data frame, matrix, or gt table to convert. |
format |
Output format: "markdown", "html", "latex", "rst", "pipe". Default "pipe" for GitHub-flavored markdown. |
digits |
Number of decimal places for numeric columns. Default 2. |
caption |
Optional table caption. |
col.names |
Optional column names (overrides data frame names). |
row.names |
Logical. Include row names? Default FALSE. |
align |
Column alignment: "l" (left), "c" (center), "r" (right), or a vector of alignments. |
... |
Additional arguments passed to knitr::kable. |
A knitr_kable object.
## Not run: df <- data.frame(A = 1:3, B = c("x", "y", "z")) to_kable(df) to_kable(df, format = "html", caption = "My Table") ## End(Not run)## Not run: df <- data.frame(A = 1:3, B = c("x", "y", "z")) to_kable(df) to_kable(df, format = "html", caption = "My Table") ## End(Not run)
Converts a data frame or gt table to LaTeX tabular format. Works with any tabular data structure.
to_latex( x, title = NULL, label = NULL, digits = 2, align = "l", booktabs = TRUE, float = NULL, position = "htbp" )to_latex( x, title = NULL, label = NULL, digits = 2, align = "l", booktabs = TRUE, float = NULL, position = "htbp" )
x |
A data frame, matrix, or gt table to convert. |
title |
Optional title (added as caption). |
label |
Optional LaTeX label for cross-referencing. |
digits |
Number of decimal places for numeric columns. Default 2. |
align |
Character vector of column alignments ("l", "c", "r") or single character to apply to all columns. Default "l" (left). |
booktabs |
Logical. Use booktabs style (toprule, midrule, bottomrule)? Default TRUE for cleaner tables. |
float |
Logical. Wrap in table environment with caption? Default TRUE if title is provided. |
position |
Table float position (e.g., "htbp"). Default "htbp". |
A character string containing the LaTeX code with class "latex_table" for proper printing.
## Not run: # Convert a data frame to LaTeX df <- data.frame( Variable = c("Age", "Score", "Income"), Mean = c(35.2, 78.5, 52000), SD = c(10.1, 12.3, 15000) ) to_latex(df) to_latex(df, title = "Descriptive Statistics", booktabs = TRUE) # With custom alignment to_latex(df, align = c("l", "r", "r")) ## End(Not run)## Not run: # Convert a data frame to LaTeX df <- data.frame( Variable = c("Age", "Score", "Income"), Mean = c(35.2, 78.5, 52000), SD = c(10.1, 12.3, 15000) ) to_latex(df) to_latex(df, title = "Descriptive Statistics", booktabs = TRUE) # With custom alignment to_latex(df, align = c("l", "r", "r")) ## End(Not run)
Converts a data frame or gt table to markdown format. Works with any tabular data structure.
to_markdown( x, title = NULL, subtitle = NULL, digits = 2, align = "l", caption_style = c("header", "bold", "plain") )to_markdown( x, title = NULL, subtitle = NULL, digits = 2, align = "l", caption_style = c("header", "bold", "plain") )
x |
A data frame, matrix, or gt table to convert. |
title |
Optional title for the table. |
subtitle |
Optional subtitle for the table. |
digits |
Number of decimal places for numeric columns. Default 2. |
align |
Character vector of column alignments ("l", "c", "r") or single character to apply to all columns. Default "l" (left). |
caption_style |
Style for title: "header" (## Title), "bold" (**Title**), or "plain". Default "header". |
A character string containing the markdown table with class "markdown_table" for proper printing.
## Not run: # Convert a data frame to markdown df <- data.frame( Name = c("Alice", "Bob", "Carol"), Score = c(85.5, 92.3, 78.9), Grade = c("B", "A", "C") ) to_markdown(df) to_markdown(df, title = "Student Scores", digits = 1) # Works with gt tables too library(gt) gt_table <- gt(df) to_markdown(gt_table) ## End(Not run)## Not run: # Convert a data frame to markdown df <- data.frame( Name = c("Alice", "Bob", "Carol"), Score = c(85.5, 92.3, 78.9), Grade = c("B", "A", "C") ) to_markdown(df) to_markdown(df, title = "Student Scores", digits = 1) # Works with gt tables too library(gt) gt_table <- gt(df) to_markdown(gt_table) ## End(Not run)
Vectorized winsorization for use with dplyr. For group-wise winsorization, use dplyr::group_by() before mutate().
winsorize_vec( x, method = c("zscore", "iqr", "percentile"), threshold = NULL, na.rm = TRUE )winsorize_vec( x, method = c("zscore", "iqr", "percentile"), threshold = NULL, na.rm = TRUE )
x |
Numeric vector. |
method |
Detection method: "zscore", "iqr", or "percentile". |
threshold |
Threshold value. |
na.rm |
Logical. Remove NA values? Default TRUE. |
Winsorized numeric vector.
## Not run: library(dplyr) # Winsorize at 3 SD mtcars %>% mutate(hp_w = winsorize_vec(hp, method = "zscore", threshold = 3)) # Winsorize at 5th/95th percentile mtcars %>% mutate(hp_w = winsorize_vec(hp, method = "percentile", threshold = 0.05)) # Group-wise winsorization mtcars %>% group_by(cyl) %>% mutate(hp_w = winsorize_vec(hp)) ## End(Not run)## Not run: library(dplyr) # Winsorize at 3 SD mtcars %>% mutate(hp_w = winsorize_vec(hp, method = "zscore", threshold = 3)) # Winsorize at 5th/95th percentile mtcars %>% mutate(hp_w = winsorize_vec(hp, method = "percentile", threshold = 0.05)) # Group-wise winsorization mtcars %>% group_by(cyl) %>% mutate(hp_w = winsorize_vec(hp)) ## End(Not run)