Package {mariposa}


Type: Package
Title: 'SPSS'-Compatible Statistical Tools for Survey Data
Version: 0.7.3
Description: Statistical analysis of survey data with full support for survey weights, grouped operations, and 'tidyverse' integration. Provides 80 functions for data import/export ('SPSS', 'Stata', 'SAS', 'Excel') with label roundtripping and tagged NA preservation, label management (variable labels, value labels, type conversions, missing value declaration), data transformation (recoding, dummy coding, standardization, centering), descriptive statistics, codebook generation, hypothesis testing, correlation analysis, post-hoc comparisons, weighted statistics, scale analysis, regression, non-parametric tests, exact tests, factorial ANOVA, and ANCOVA. Every analysis offers compact print() and detailed summary() output with toggleable sections. Statistical results are validated against 'SPSS' version 29 within documented per-tier tolerances (see the compatibility vignette for per-function status). Methods follow the published algorithms of IBM Corp. (2023, "IBM SPSS Statistics Algorithms"), the Lilliefors-corrected normality test of Dallal and Wilkinson (1986) <doi:10.1080/00031305.1986.10475419>, and the adjusted standardized residuals of Haberman (1973) <doi:10.2307/2529686>. Designed for survey researchers, social scientists, and students working with complex survey designs.
License: MIT + file LICENSE
Language: en
Encoding: UTF-8
Depends: R (≥ 4.1.0)
Imports: cli (≥ 3.0.0), htmltools (≥ 0.5.0), stats, utils, dplyr (≥ 1.0.0), rlang (≥ 1.0.0), tidyselect (≥ 1.1.0), tibble (≥ 3.0.0)
Suggests: testthat (≥ 3.0.0), knitr, rmarkdown, covr, haven (≥ 2.4.0), GPArotation, MASS, openxlsx2, survey, broom, psych, lavaan, semTools, nortest
VignetteBuilder: knitr
LazyData: true
Config/testthat/edition: 3
URL: https://YannickDiehl.github.io/mariposa/, https://github.com/YannickDiehl/mariposa
BugReports: https://github.com/YannickDiehl/mariposa/issues
Config/roxygen2/version: 8.0.0
NeedsCompilation: no
Packaged: 2026-09-17 19:47:08 UTC; yannickdiehl
Author: Yannick Diehl [aut, cre]
Maintainer: Yannick Diehl <yannick.diehl@gmail.com>
Repository: CRAN
Date/Publication: 2026-09-28 08:30:09 UTC

mariposa: 'SPSS'-Compatible Statistical Tools for Survey Data

Description

logo

Statistical analysis of survey data with full support for survey weights, grouped operations, and 'tidyverse' integration. Provides 80 functions for data import/export ('SPSS', 'Stata', 'SAS', 'Excel') with label roundtripping and tagged NA preservation, label management (variable labels, value labels, type conversions, missing value declaration), data transformation (recoding, dummy coding, standardization, centering), descriptive statistics, codebook generation, hypothesis testing, correlation analysis, post-hoc comparisons, weighted statistics, scale analysis, regression, non-parametric tests, exact tests, factorial ANOVA, and ANCOVA. Every analysis offers compact print() and detailed summary() output with toggleable sections. Statistical results are validated against 'SPSS' version 29 within documented per-tier tolerances (see the compatibility vignette for per-function status). Methods follow the published algorithms of IBM Corp. (2023, "IBM SPSS Statistics Algorithms"), the Lilliefors-corrected normality test of Dallal and Wilkinson (1986) doi:10.1080/00031305.1986.10475419, and the adjusted standardized residuals of Haberman (1973) doi:10.2307/2529686. Designed for survey researchers, social scientists, and students working with complex survey designs.

Author(s)

Maintainer: Yannick Diehl yannick.diehl@gmail.com

Authors:

See Also

Useful links:


Analysis of Covariance: ANCOVA

Description

ancova() tests whether group means differ after controlling for one or more continuous covariates. It performs a factorial ANCOVA using Type III Sum of Squares, matching SPSS UNIANOVA output with the WITH keyword.

Think of it as:

The test tells you:

Usage

ancova(data, dv, between, covariate, weights = NULL, ss_type = 3)

Arguments

data

Your survey data (a data frame or tibble)

dv

The numeric dependent variable to analyze (unquoted)

between

Character vector or unquoted variable names specifying the between-subjects factors (1-3 factors). These must be categorical variables (factor, character, or labelled numeric).

covariate

Unquoted variable names of the continuous covariates to control for. Use c(age, income) for multiple covariates.

weights

Optional survey weights for population-representative results (unquoted variable name)

ss_type

Deprecated; only 3 (Type III, the SPSS default) is implemented. Passing 2 issues a warning and computes Type III.

Details

Understanding the Results

Adjusted Means (Estimated Marginal Means): These are the group means after statistically removing the effect of the covariate(s). They answer: "What would the group means be if all groups had the same covariate values?"

Covariate Effects: The covariate row in the ANOVA table shows whether the covariate significantly predicts the DV after adjusting for the factors.

Factor Effects: These show whether the factor affects the DV after controlling for the covariate. This is the primary test of interest.

Partial Eta Squared (Effect Size):

When to Use This

Use ANCOVA when:

Value

An object of class "ancova" containing:

anova_table

Tibble with Source, SS, df, MS, F, p, Partial Eta Squared

parameter_estimates

Tibble with regression coefficients (B, SE, t, p)

descriptives

Tibble with unadjusted cell means, SDs, and Ns

estimated_marginal_means

Tibble with adjusted means (covariates at grand mean)

levene_test

Tibble with Levene's test results

r_squared

R-squared and Adjusted R-squared

model

The underlying lm model object

call_info

List with metadata (dv, factors, covariates, weighted, etc.)

Use summary() for the full SPSS-style output with toggleable sections.

References

Huitema, B. E. (2011). The Analysis of Covariance and Alternatives (2nd ed.). Wiley.

IBM Corp. (2023). IBM SPSS Statistics 29 Algorithms. IBM Corporation.

See Also

factorial_anova for ANOVA without covariates.

linear_regression for regression analysis.

oneway_anova for single-factor ANOVA.

summary.ancova for detailed output with toggleable sections.

Other hypothesis_tests: binomial_test(), chi_square(), chisq_gof(), factorial_anova(), fisher_test(), friedman_test(), kruskal_wallis(), mann_whitney(), mcnemar_test(), oneway_anova(), t_test(), wilcoxon_test()

Examples

# Load required packages and data
library(dplyr)
data(survey_data)

# One-way ANCOVA: income by education, controlling for age
survey_data %>%
  ancova(dv = income, between = c(education), covariate = c(age))

# Two-way ANCOVA with weights
survey_data %>%
  ancova(dv = income, between = c(gender, education),
         covariate = c(age), weights = sampling_weight)

# Multiple covariates
survey_data %>%
  ancova(dv = income, between = c(education),
         covariate = c(age, political_orientation))

# --- Three-layer output ---
result <- ancova(survey_data, dv = income, between = c(education),
                 covariate = c(age))
result              # compact overview
summary(result)     # full detailed output with all sections
summary(result, marginal_means = FALSE)  # hide estimated marginal means


ANOVA for a linear_regression model

Description

For listwise + ungrouped results, dispatches to stats::anova.lm (sequential Type-I sum of squares per term). For the SPSS-style overall-model ANOVA table, use object$anova_table.

Usage

## S3 method for class 'linear_regression'
anova(object, ...)

Arguments

object

A linear_regression result.

...

Passed to stats::anova.lm.

Value

An anova table (sequential Type-I sums of squares), as returned by stats::anova.lm.


ANOVA for a logistic_regression model

Description

For ungrouped results, dispatches to stats::anova.glm (sequential deviance per term). For the SPSS-style omnibus chi-square test, use object$omnibus_test.

Usage

## S3 method for class 'logistic_regression'
anova(object, ...)

Arguments

object

A logistic_regression result.

...

Passed to stats::anova.glm.

Value

An anova table (sequential analysis of deviance per term), as returned by stats::anova.glm.


Test Whether a Proportion Matches an Expected Value

Description

binomial_test() tests whether the observed proportion of a binary variable differs from a hypothesized proportion. It uses the exact binomial test, making it valid for any sample size.

Think of it as:

The test tells you:

Usage

binomial_test(data, ..., p = 0.5, weights = NULL, conf.level = 0.95)

Arguments

data

Your survey data (a data frame or tibble)

...

One or more binary variables to test. Each must have exactly 2 categories (e.g., Yes/No, Male/Female, 0/1, TRUE/FALSE)

p

The hypothesized proportion to test against (Default: 0.50 = 50 percent). This refers to the proportion of the first category (first factor level, or the lower numeric value).

weights

Optional survey weights for population-representative results

conf.level

Confidence level for intervals (Default: 0.95 = 95 percent)

Details

Understanding the Results

P-value: If p < 0.05, the proportion differs significantly from the test proportion

Observed Proportion: The actual proportion in your data. Compare this with the test proportion to see the direction of any difference.

Confidence Interval: The range likely to contain the true population proportion. If the test proportion falls outside this range, the result is significant.

When to Use This

Use the binomial test when:

Relationship to Other Tests

Weighted variants

SPSS NPAR TESTS ignores WEIGHT BY, so weighted results have no SPSS reference. The weighted variant is an R-only frequency-weight extension that reduces exactly to the unweighted test when all weights equal 1 (enforced by an internal invariance suite); see vignette("spss-compatibility") for validation status.

Results will be very similar to a one-sample z-test for proportions

Value

Test results showing whether the proportion differs from expected, including:

References

Conover, W. J. (1999). Practical nonparametric statistics (3rd ed.). John Wiley & Sons.

See Also

binom.test for the base R exact binomial test.

chi_square for testing associations between categorical variables.

Other hypothesis_tests: ancova(), chi_square(), chisq_gof(), factorial_anova(), fisher_test(), friedman_test(), kruskal_wallis(), mann_whitney(), mcnemar_test(), oneway_anova(), t_test(), wilcoxon_test()

Examples

# Load required packages and data
library(dplyr)
data(survey_data)

# Test whether gender split is 50/50
survey_data %>%
  binomial_test(gender, p = 0.50)

# Test whether East region proportion is 50%
survey_data %>%
  binomial_test(region, p = 0.50)

# Multiple variables at once
survey_data %>%
  binomial_test(gender, region, p = 0.50)

# Weighted analysis
survey_data %>%
  binomial_test(gender, p = 0.50, weights = sampling_weight)

# Grouped analysis (separate test per region)
survey_data %>%
  group_by(region) %>%
  binomial_test(gender, p = 0.50)


Center Variables (Mean Centering)

Description

Centers variables by subtracting the mean. When used on a grouped data frame (via dplyr::group_by()), this becomes group-mean centering — the R equivalent of separate centering within each group.

Usage

center(data, ..., weights = NULL, suffix = NULL, na.rm = TRUE)

Arguments

data

A data frame or numeric vector.

...

Variables to center (tidyselect). Only used when data is a data frame.

weights

Optional survey weights (unquoted column name or numeric vector). When provided, the weighted mean is subtracted instead of the unweighted mean.

suffix

A character string appended to column names (e.g., "_c"). If NULL (default), original columns are overwritten.

na.rm

Remove missing values before computing the mean? Default: TRUE.

Details

Grand-Mean vs. Group-Mean Centering

Weighted Centering

When weights is provided, the weighted mean is used for centering. This accounts for survey design in the centering computation.

Value

If data is a vector, a centered numeric vector. If data is a data frame, the modified data frame (invisibly).

See Also

std() for full standardization (centering + scaling)

Other transform: std()

Examples

library(dplyr)
data(survey_data)

# Grand-mean centering
data <- center(survey_data, income, age, suffix = "_c")

# Weighted centering
data <- center(survey_data, income, age,
               weights = sampling_weight, suffix = "_c")

# Group-mean centering (replaces sjmisc::de_mean)
data <- survey_data %>%
  group_by(region) %>%
  center(income, age, suffix = "_gmc")


Test If Two Categories Are Related

Description

chi_square() helps you discover if two categorical variables are related or independent. For example, is education level related to voting preference? Or are they independent of each other?

The test tells you:

Usage

chi_square(data, ..., weights = NULL, correct = FALSE)

Arguments

data

Your survey data (a data frame or tibble)

...

Two categorical variables to test (e.g., gender, region)

weights

Optional survey weights for population-representative results

correct

Apply continuity correction for small samples? (Default: FALSE)

Details

Understanding the Results

P-value: If p < 0.05, the variables are likely related (not independent)

Effect Sizes (How strong is the relationship?):

When to Use This

Use chi-squared test when:

Reading the Frequency Tables

Tips for Success

Value

Test results showing whether the variables are related, including:

References

Pearson, K. (1900). On the criterion that a given system of deviations from the probable in the case of a correlated system of variables is such that it can be reasonably supposed to have arisen from random sampling. Philosophical Magazine, 50(302), 157–175.

Cramer, H. (1946). Mathematical Methods of Statistics. Princeton University Press.

IBM Corp. (2023). IBM SPSS Statistics 29 Algorithms. IBM Corporation.

See Also

chisq.test for the base R chi-squared test.

crosstab for detailed cross-tabulation tables.

frequency for single-variable frequency tables.

summary.chi_square for detailed output with toggleable sections.

Other hypothesis_tests: ancova(), binomial_test(), chisq_gof(), factorial_anova(), fisher_test(), friedman_test(), kruskal_wallis(), mann_whitney(), mcnemar_test(), oneway_anova(), t_test(), wilcoxon_test()

Examples

# Load required packages and data
library(dplyr)
data(survey_data)

# Basic chi-squared test for independence
survey_data %>% chi_square(gender, region)

# With weights
survey_data %>% chi_square(gender, education, weights = sampling_weight)

# Grouped analysis
survey_data %>% 
  group_by(region) %>% 
  chi_square(gender, employment)

# With continuity correction
survey_data %>% chi_square(gender, region, correct = TRUE)

# --- Three-layer output ---
result <- chi_square(survey_data, gender, education)
result              # compact one-line overview
summary(result)     # full detailed output with all sections
summary(result, cross_tabulation = FALSE)  # hide cross-tabulation


Chi-Square Goodness-of-Fit Test

Description

chisq_gof() tests whether observed frequencies of a categorical variable match expected frequencies. By default, it tests against equal proportions (uniform distribution). You can also specify custom expected proportions.

Think of it as:

The test tells you:

Usage

chisq_gof(data, ..., expected = NULL, weights = NULL)

Arguments

data

Your survey data (data frame or tibble)

...

One or more categorical variables to test (tidyselect supported)

expected

Optional numeric vector of expected proportions (must sum to 1). Only used when a single variable is tested. If NULL (default), equal proportions are assumed.

weights

Optional survey weights for population-representative results

Details

Understanding the Results

P-value: If p < 0.05, the distribution differs from expected

Residuals: The difference between observed and expected counts. Large positive residuals indicate a category has more cases than expected; large negative residuals indicate fewer cases than expected.

When to Use This

Use this test when:

The Chi-Square Goodness-of-Fit Statistic

\chi^2 = \sum \frac{(O_i - E_i)^2}{E_i}

where O_i = observed frequency, E_i = expected frequency.

Degrees of freedom = number of categories - 1.

Relationship to Other Tests

SPSS Equivalent

SPSS: NPAR TESTS /CHISQUARE=variable /EXPECTED=EQUAL or: NPAR TESTS /CHISQUARE=variable /EXPECTED=50 30 20

Value

Test results showing whether observed frequencies match expected, including:

References

Pearson, K. (1900). On the criterion that a given system of deviations from the probable in the case of a correlated system of variables is such that it can be reasonably supposed to have arisen from random sampling. Philosophical Magazine, 50(302), 157-175.

See Also

chi_square for chi-square test of independence (two variables).

binomial_test for testing a single proportion.

Other hypothesis_tests: ancova(), binomial_test(), chi_square(), factorial_anova(), fisher_test(), friedman_test(), kruskal_wallis(), mann_whitney(), mcnemar_test(), oneway_anova(), t_test(), wilcoxon_test()

Examples

# Load required packages and data
library(dplyr)
data(survey_data)

# Test whether gender is equally distributed
survey_data %>%
  chisq_gof(gender)

# Test multiple variables at once
survey_data %>%
  chisq_gof(gender, region, education)

# Custom expected proportions
survey_data %>%
  chisq_gof(interview_mode, expected = c(0.5, 0.3, 0.2))

# With weights
survey_data %>%
  chisq_gof(gender, weights = sampling_weight)

# Grouped analysis
survey_data %>%
  group_by(region) %>%
  chisq_gof(education)


Create a Codebook for Your Data

Description

codebook() creates an interactive HTML data dictionary that opens in the RStudio Viewer. It shows you everything about your dataset at a glance: variable names, types, labels, the empirical values found in the data, value labels, and frequency counts.

Think of it as a professional "cheat sheet" for your dataset – especially useful when working with labelled survey data imported from SPSS, Stata, or SAS.

Usage

codebook(
  data,
  ...,
  weights = NULL,
  show_id = TRUE,
  show_type = TRUE,
  show_labels = TRUE,
  show_values = TRUE,
  show_freq = TRUE,
  show_na = TRUE,
  show_unused = FALSE,
  max_values = 10,
  max_len = 50,
  sort_by_name = FALSE,
  file = NULL,
  view = interactive()
)

Arguments

data

Your survey data (a data frame or tibble)

...

Optional: specific variables to include. If empty, all variables are shown. Supports tidyselect helpers like starts_with("trust").

weights

Optional survey weights for weighted frequency calculations

show_id

Show variable position number? (Default: TRUE)

show_type

Show data type? (Default: TRUE)

show_labels

Show variable labels? (Default: TRUE)

show_values

Show empirical values and value labels? (Default: TRUE)

show_freq

Show frequency counts? (Default: TRUE)

show_na

Show tagged missing value types in the codebook? (Default: TRUE). When data was imported with read_spss(), read_stata(), read_sas(), or read_xpt() using tagged NAs, they are displayed with their original missing value codes, labels, and frequencies below the valid values, separated by a thin gray line.

show_unused

Show all defined value labels, even those with zero observations? (Default: FALSE). Useful for seeing the full codebook including response options that no respondent selected.

max_values

Maximum number of values to display per variable before truncating or showing a range (Default: 10)

max_len

Maximum character width for labels before truncation (Default: 50)

sort_by_name

Sort variables alphabetically instead of by position? (Default: FALSE)

file

Path to save the HTML codebook. If NULL (default), no file is written unless the codebook is opened in the Viewer (then a temporary file is used). The directory of file must already exist.

view

Open the HTML codebook in the RStudio Viewer (or browser)? Defaults to interactive(), so interactive sessions open the Viewer and scripts/tests do not. Set view = FALSE to suppress the Viewer side effect entirely; ⁠file =⁠ writing is unaffected by this argument.

Details

What the Codebook Shows

For each variable, the codebook displays (depending on options):

When to Use This

Use codebook() when you:

Value

Invisibly returns a list of class "codebook" containing:

codebook

Tibble with one row per variable and all metadata

data_info

List with dataset-level information (name, nrow, ncol, etc.)

html

The generated HTML as an htmltools object

weights

Name of the weight variable, or NULL

options

List of all display options

frequencies

Named list of frequency tables per variable

See Also

describe() for detailed numeric summaries, frequency() for detailed frequency tables, read_spss(), read_por(), read_stata(), read_sas(), read_xpt() for importing data with tagged NAs

Examples

data(survey_data)

# Compact console overview (no Viewer)
cb <- codebook(survey_data)
print(cb)

# Detailed console output
summary(cb)


# Full codebook (opens in RStudio Viewer when interactive)
codebook(survey_data)

# Only trust-related variables
codebook(survey_data, starts_with("trust"))

# Save to file for sharing
codebook(survey_data, file = tempfile(fileext = ".html"))



Copy Labels from One Data Frame to Another

Description

Copies variable labels, value labels, and tagged NA metadata from a source data frame to a target data frame. This is essential after dplyr operations like dplyr::filter(), dplyr::select(), or dplyr::mutate() which can strip label attributes.

Usage

copy_labels(data, source)

Arguments

data

The target data frame (e.g., after filtering or subsetting).

source

The source data frame with the original labels.

Details

The following attributes are copied for each shared column:

Value

The target data frame with labels copied from the source. Only columns present in both data frames are affected. Columns only in the target are left unchanged.

See Also

var_label(), val_labels()

Other labels: drop_labels(), find_var(), set_na(), to_character(), to_label(), to_labelled(), to_numeric(), unlabel(), val_labels(), var_label()

Examples

# Labels are lost after dplyr operations
data_subset <- dplyr::filter(survey_data, age >= 18)

# Restore them
data_subset <- copy_labels(data_subset, survey_data)


Compare Two Categories: See How They Relate

Description

crosstab() shows you how two categorical variables relate to each other. It creates a table that reveals patterns - like whether education level differs by region, or if gender influences product preferences.

Think of it as a two-way frequency table that shows:

Usage

crosstab(
  data,
  row,
  col,
  weights = NULL,
  percentages = c("row", "none", "col", "total", "all"),
  na.rm = TRUE,
  digits = 1
)

Arguments

data

Your survey data (a data frame or tibble)

row

The variable for table rows (e.g., education, age_group)

col

The variable for table columns (e.g., region, gender)

weights

Optional survey weights for population-representative results

percentages

Which percentages to show:

  • "row" (default): Percentages across each row (adds to 100% horizontally)

  • "col": Percentages down each column (adds to 100% vertically)

  • "total": Percentage of the entire table

  • "all": Show all three types

  • "none": Just counts, no percentages

na.rm

Remove missing values before calculating? (Default: TRUE)

digits

Decimal places for percentages (Default: 1)

Details

Understanding the Results

The crosstab table shows:

When to Use This

Use crosstab when you want to:

Choosing Percentages

Tips for Success

Value

A cross-tabulation table showing the relationship between two variables. The result also carries the expected cell counts ($expected) and adjusted standardized residuals ($adj_residuals); display the residuals with summary(result, residuals = TRUE).

See Also

table for base R contingency tables.

frequency for single-variable frequency tables.

chi_square for testing if the cross-tabulated variables are related.

Other descriptive: describe(), frequency(), multiple_response(), normality_test()

Examples

# Load required packages and data
library(dplyr)
data(survey_data)

# Basic crosstab
survey_data %>% crosstab(gender, region)

# With weights and all percentages
survey_data %>% crosstab(gender, education,
                         weights = sampling_weight,
                         percentages = "all")

# Grouped analysis
survey_data %>%
  group_by(employment) %>%
  crosstab(gender, region, weights = sampling_weight)

# Column percentages only
survey_data %>% crosstab(education, employment, percentages = "col")


Get to Know Your Numeric Data

Description

describe() gives you a complete summary of numeric variables - like age, income, or satisfaction scores. It's your first step in any analysis, helping you understand what's typical, what's unusual, and how spread out your data is.

Think of it as a health check for your data that reveals:

Usage

describe(
  data,
  ...,
  weights = NULL,
  show = "short",
  probs = c(0.25, 0.5, 0.75),
  na.rm = TRUE,
  excess = TRUE
)

Arguments

data

Your survey data (a data frame or tibble)

...

The numeric variables you want to summarize. List them separated by commas, or use helpers like starts_with("trust")

weights

Optional survey weights for population-representative results. Without weights, you describe your sample. With weights, you describe the population.

show

Which statistics to display:

  • "short" (default): Essential stats (mean, median, SD, range, IQR, skewness)

  • "all": Everything including variance, kurtosis, mode, quantiles

  • Custom list: Choose specific stats like c("mean", "sd", "range")

probs

For quantiles, which percentiles to show (default: 25th, 50th, 75th)

na.rm

Remove missing values before calculating? (Default: TRUE)

excess

For kurtosis, show excess kurtosis? (Default: TRUE, easier to interpret)

Details

Understanding the Results

Key statistics and what they tell you:

When to Use This

Always start here! Use describe() to:

Interpreting Patterns

Value

A summary table with descriptive statistics for each variable

See Also

summary for base R summary statistics.

frequency for categorical variable summaries.

w_mean, w_sd, w_median for individual weighted statistics.

t_test and oneway_anova for group comparisons.

Other descriptive: crosstab(), frequency(), multiple_response(), normality_test()

Examples

# Load required packages and data
library(dplyr)
data(survey_data)

# Basic unweighted analysis
survey_data %>% describe(age)

# Weighted analysis
survey_data %>% describe(age, weights = sampling_weight)

# Multiple variables with custom statistics
survey_data %>% describe(age, income, life_satisfaction, 
                        weights = sampling_weight, 
                        show = c("mean", "sd", "skew"))

# Grouped analysis
survey_data %>% 
  group_by(region) %>% 
  describe(age, weights = sampling_weight)


Remove Unused Value Labels

Description

Removes value labels for values that are not present in the data. This is useful after filtering or subsetting, when some categories may no longer exist but their labels remain attached.

Usage

drop_labels(data, ..., drop_na = FALSE)

Arguments

data

A data frame or a single vector.

...

Optional: unquoted variable names (tidyselect supported). If empty, applies to all labelled columns.

drop_na

If TRUE, also removes tagged NA labels. Default: FALSE (tagged NA labels are preserved even if no tagged NAs of that type exist).

Details

This is useful after subsetting data (e.g., filtering out a category). The removed category's label still exists on the variable, which can cause confusing output in frequency() or codebook(). drop_labels() cleans this up by keeping only labels for values actually present in the data.

By default, tagged NA labels are preserved (drop_na = FALSE) because they represent missing value types, not substantive categories.

Value

The data with unused labels removed.

See Also

val_labels(), copy_labels()

Other labels: copy_labels(), find_var(), set_na(), to_character(), to_label(), to_labelled(), to_numeric(), unlabel(), val_labels(), var_label()

Examples

# After filtering, region == 4 no longer exists but its label remains
data_subset <- dplyr::filter(survey_data, region != 4)
data_clean <- drop_labels(data_subset)


Find Which Specific Groups Differ After Kruskal-Wallis

Description

dunn_test() tells you exactly which groups are different from each other after Kruskal-Wallis finds overall differences. It's the non-parametric equivalent of a Tukey or Scheffe post-hoc test.

Think of it as:

Usage

dunn_test(x, ...)

## Default S3 method:
dunn_test(x, ...)

Arguments

x

Kruskal-Wallis results from kruskal_wallis()

...

Additional arguments passed to methods. The method for kruskal_wallis objects accepts p_adjust (character): method for adjusting p-values for multiple comparisons. Options: "bonferroni" (default, most conservative), "holm", "BH", "hochberg", "hommel", "BY", "fdr", "none".

Details

Understanding the Results

Z-Statistics: Based on differences in mean ranks between groups

Adjusted P-values: Control for multiple comparisons

The Dunn Test Formula

For each pair of groups (i, j):

Z_{ij} = \frac{\bar{R}_i - \bar{R}_j}{\sqrt{\frac{N(N+1)}{12} \left(\frac{1}{n_i} + \frac{1}{n_j}\right)}}

where \bar{R}_i is the mean rank for group i, N is the total sample size, and n_i is the size of group i.

P-Value Adjustment Methods

When to Use This

Use Dunn test when:

Relationship to Other Tests

Weighted variants

When the parent kruskal_wallis() result is weighted, the pairwise z statistics use the same frequency-weighted midranks. SPSS NPAR TESTS ignores WEIGHT BY, so weighted results have no SPSS reference (R-only, guarded by an internal invariance suite); see vignette("spss-compatibility") for validation status.

Value

Pairwise comparison results showing:

References

Dunn, O. J. (1964). Multiple comparisons using rank sums. Technometrics, 6(3), 241-252.

See Also

kruskal_wallis for performing Kruskal-Wallis tests.

tukey_test for parametric post-hoc comparisons after ANOVA.

scheffe_test for conservative parametric post-hoc comparisons.

Other posthoc: levene_test(), pairwise_wilcoxon(), scheffe_test(), tukey_test()

Examples

# Load required packages and data
library(dplyr)
data(survey_data)

# Perform Kruskal-Wallis followed by Dunn post-hoc test
kw_result <- survey_data %>%
  kruskal_wallis(life_satisfaction, group = education)

# Dunn post-hoc comparisons (default: Bonferroni)
kw_result %>% dunn_test()

# With Holm correction (less conservative)
kw_result %>% dunn_test(p_adjust = "holm")

# With Benjamini-Hochberg (controls false discovery rate)
kw_result %>% dunn_test(p_adjust = "BH")

# With weights
kw_weighted <- survey_data %>%
  kruskal_wallis(life_satisfaction, group = education,
                 weights = sampling_weight)

kw_weighted %>% dunn_test()

# Multiple variables
kw_multi <- survey_data %>%
  kruskal_wallis(life_satisfaction, trust_government,
                 group = education)

kw_multi %>% dunn_test()

# Grouped analysis
kw_grouped <- survey_data %>%
  group_by(region) %>%
  kruskal_wallis(life_satisfaction, group = education)

kw_grouped %>% dunn_test()


Explore the Structure Behind Your Survey Items

Description

efa() performs Exploratory Factor Analysis (EFA) to discover underlying patterns in your survey items. Supports both Principal Component Analysis (PCA) and Maximum Likelihood (ML) extraction. This is the R equivalent of SPSS's FACTOR procedure.

For example, if you have 6 items measuring different attitudes, EFA can reveal whether they group into 2-3 underlying dimensions (factors or components).

Usage

efa(
  data,
  ...,
  n_factors = NULL,
  rotation = "varimax",
  extraction = "pca",
  weights = NULL,
  use = "pairwise",
  sort = TRUE,
  blank = 0.4,
  na.rm = TRUE
)

Arguments

data

Your survey data (a data frame or tibble)

...

The items to analyze. Use bare column names separated by commas, or tidyselect helpers like starts_with("trust").

n_factors

Number of components to extract. Default NULL uses the Kaiser criterion (eigenvalue > 1).

rotation

Rotation method: "varimax" (default, orthogonal), "oblimin" (oblique, allows correlated factors), "promax" (oblique, power-based), or "none".

extraction

Extraction method: "pca" (default, Principal Component Analysis) or "ml" (Maximum Likelihood, enables goodness-of-fit testing, assumes multivariate normality).

weights

Optional survey weights for population-representative results.

use

How to handle missing data for correlation computation: "pairwise" (default, matches SPSS) or "complete" (listwise).

sort

Logical. Sort loadings by size within each component? Default TRUE.

blank

Numeric. Suppress (hide) loadings with absolute value below this threshold in the print output. Default 0.40 (matches SPSS BLANK(.40)). Set to 0 to show all loadings.

na.rm

Logical. Remove missing values? Default TRUE.

Details

Understanding the Results

KMO (Kaiser-Meyer-Olkin) measures sampling adequacy:

Bartlett's Test of Sphericity tests whether correlations are significantly different from zero. A significant result (p < .05) means the correlation matrix is suitable for factor analysis.

Eigenvalues indicate how much variance each component explains. The Kaiser criterion retains components with eigenvalue > 1.

Factor Loadings show how strongly each item relates to each component:

Communalities show how much of each item's variance is explained by the extracted components. Low communalities (< 0.40) suggest the item doesn't fit well with the others.

Choosing an Extraction Method

Choosing a Rotation

Value

An efa result object containing:

loadings

Component loading matrix (rotated if rotation applied)

unrotated_loadings

Unrotated component matrix

eigenvalues

All eigenvalues from the correlation matrix

variance_explained

Tibble with Total, % of Variance, Cumulative %

rotation_variance

Tibble with rotation sums of squared loadings

communalities

Extraction communalities for each variable

kmo

List with overall KMO and per-item MSA values

bartlett

List with chi_sq, df, and p_value

rotation

Rotation method used

extraction

Extraction method used

n_factors

Number of components extracted

correlation_matrix

Correlation matrix used for analysis

initial_communalities

Initial communalities (1.0 for PCA, SMC for ML)

goodness_of_fit

Goodness-of-fit test (ML only): chi_sq, df, p_value. NULL for PCA.

uniquenesses

Unique variances per variable (ML only, NULL for PCA)

pattern_matrix

Pattern matrix (oblimin/promax only, NULL otherwise)

structure_matrix

Structure matrix (oblimin/promax only, NULL otherwise)

factor_correlations

Factor correlation matrix (oblimin/promax only, NULL otherwise)

variables

Character vector of variable names

weights

Weights variable name or NULL

n

Sample size

col_prefix

Column name prefix: "PC" for PCA, "Factor" for ML

sort

Whether loadings are sorted

blank

Suppression threshold

Use summary() for the full SPSS-style output with toggleable sections.

See Also

reliability for checking scale reliability before creating indices.

row_means for creating mean indices after identifying factors.

summary.efa for detailed output with toggleable sections.

Other scale: pomps(), reliability(), row_count(), row_means(), row_sums()

Examples

library(dplyr)
data(survey_data)

# Basic EFA with Varimax rotation
efa(survey_data,
    political_orientation, environmental_concern, life_satisfaction,
    trust_government, trust_media, trust_science)

# With Oblimin rotation (requires GPArotation package)

if (requireNamespace("GPArotation", quietly = TRUE)) {
  efa(survey_data,
      political_orientation, environmental_concern, life_satisfaction,
      trust_government, trust_media, trust_science,
      rotation = "oblimin")
}


# Maximum Likelihood extraction
efa(survey_data,
    political_orientation, environmental_concern, life_satisfaction,
    trust_government, trust_media, trust_science,
    extraction = "ml")

# Promax rotation (oblique)
efa(survey_data,
    political_orientation, environmental_concern, life_satisfaction,
    trust_government, trust_media, trust_science,
    rotation = "promax")

# Fix number of factors
efa(survey_data,
    political_orientation, environmental_concern, life_satisfaction,
    trust_government, trust_media, trust_science,
    n_factors = 2)

# With survey weights
efa(survey_data,
    political_orientation, environmental_concern, life_satisfaction,
    trust_government, trust_media, trust_science,
    weights = sampling_weight)

# Grouped by region
survey_data %>%
  group_by(region) %>%
  efa(political_orientation, environmental_concern, life_satisfaction,
      trust_government, trust_media, trust_science)

# --- Three-layer output ---
result <- efa(survey_data, political_orientation, environmental_concern,
              life_satisfaction, trust_government, trust_media, trust_science)
result              # compact overview
summary(result)     # full detailed output with all sections
summary(result, communalities = FALSE)  # hide communalities table


Compare Groups Across Multiple Factors: Factorial ANOVA

Description

factorial_anova() tests whether group means differ across two or more factors simultaneously, including their interactions. It performs a factorial (two-way, three-way) ANOVA using Type III Sum of Squares, matching SPSS UNIANOVA output.

Think of it as:

The test tells you:

Usage

factorial_anova(data, dv, between, weights = NULL, ss_type = 3)

Arguments

data

Your survey data (a data frame or tibble)

dv

The numeric dependent variable to analyze (unquoted)

between

Character vector or unquoted variable names specifying the between-subjects factors (2-3 factors). These must be categorical variables (factor, character, or labelled numeric).

weights

Optional survey weights for population-representative results (unquoted variable name)

ss_type

Deprecated; only 3 (Type III, the SPSS default) is implemented. Passing 2 issues a warning and computes Type III.

Details

Understanding the Results

Main Effects: Does each factor independently affect the outcome?

Interaction Effects: Does the effect of one factor depend on another?

Partial Eta Squared (Effect Size):

Type III Sum of Squares

Type III SS tests each effect after adjusting for all other effects. This is the standard in SPSS and recommended for unbalanced designs (unequal cell sizes). It uses orthogonal contrasts (contr.sum) internally.

When to Use This

Use factorial ANOVA when:

What Comes Next?

If the ANOVA is significant:

  1. Check which effects are significant (main effects vs. interactions)

  2. Use tukey_test() for post-hoc comparisons on main effects

  3. Examine cell means to interpret interaction patterns

  4. Consider effect sizes for practical significance

Value

An object of class "factorial_anova" containing:

anova_table

Tibble with Source, SS, df, MS, F, p, Partial Eta Squared

descriptives

Tibble with cell means, SDs, and Ns for each factor combination

levene_test

Tibble with Levene's test results (F, df1, df2, p)

r_squared

R-squared and Adjusted R-squared

model

The underlying model object for S3 dispatch

call_info

List with metadata (dv, factors, weighted, n_total, n_missing)

Use summary() for the full SPSS-style output with toggleable sections.

References

Cohen, J. (1988). Statistical Power Analysis for the Behavioral Sciences (2nd ed.). Lawrence Erlbaum Associates.

IBM Corp. (2023). IBM SPSS Statistics 29 Algorithms. IBM Corporation.

Maxwell, S. E., & Delaney, H. D. (2004). Designing Experiments and Analyzing Data (2nd ed.). Lawrence Erlbaum Associates.

See Also

oneway_anova for single-factor ANOVA.

tukey_test for post-hoc pairwise comparisons.

levene_test for testing homogeneity of variances.

ancova for ANOVA with covariates.

summary.factorial_anova for detailed output with toggleable sections.

Other hypothesis_tests: ancova(), binomial_test(), chi_square(), chisq_gof(), fisher_test(), friedman_test(), kruskal_wallis(), mann_whitney(), mcnemar_test(), oneway_anova(), t_test(), wilcoxon_test()

Examples

# Load required packages and data
library(dplyr)
data(survey_data)

# Two-way ANOVA: income by gender and education
survey_data %>%
  factorial_anova(dv = income, between = c(gender, education))

# Two-way ANOVA with weights
survey_data %>%
  factorial_anova(dv = life_satisfaction, between = c(gender, region),
                  weights = sampling_weight)

# Three-way ANOVA
survey_data %>%
  factorial_anova(dv = income, between = c(gender, region, education))

# Follow up with post-hoc tests
result <- survey_data %>%
  factorial_anova(dv = income, between = c(gender, education))
result %>% tukey_test()
result %>% levene_test()

# --- Three-layer output ---
result              # compact overview
summary(result)     # full detailed output with all sections
summary(result, marginal_means = FALSE)  # hide estimated marginal means


Find Variables by Name or Label

Description

Searches for variables in your data by matching a pattern against variable names, variable labels, or both. This is especially useful for SPSS datasets where variable names are often cryptic codes (e.g., v104, q23a_1) and the actual meaning is stored in variable labels.

Usage

find_var(data, pattern, search = c("name_label", "name", "label"))

Arguments

data

A data frame (typically imported from SPSS with read_spss).

pattern

A search term or regular expression to match against variable names and/or labels. Case-insensitive by default.

search

Where to search: "name_label" (default) searches both variable names and labels, "name" searches only names, "label" searches only labels.

Details

When to Use This

Pattern Matching

The pattern argument supports regular expressions. Matching is case-insensitive. Some examples:

Value

A data frame with columns:

col

Column position in the data

name

Variable name

label

Variable label (or "" if none)

See Also

var_label() for getting/setting variable labels, val_labels() for value labels

Other labels: copy_labels(), drop_labels(), set_na(), to_character(), to_label(), to_labelled(), to_numeric(), unlabel(), val_labels(), var_label()

Examples

library(dplyr)
data(survey_data)

# Find all variables related to "trust"
find_var(survey_data, "trust")

# Search only in variable labels
find_var(survey_data, "satisfaction", search = "label")

# Use regex to find numbered items
find_var(survey_data, "^q[0-9]+", search = "name")


Fisher's Exact Test for Small Samples

Description

fisher_test() performs Fisher's exact test for independence in a contingency table. Use this instead of chi_square() when your sample is small or when expected cell frequencies are below 5.

Think of it as:

The test tells you:

Usage

fisher_test(data, row, col, weights = NULL, ...)

Arguments

data

Your survey data (data frame or tibble)

row

The row variable (categorical)

col

The column variable (categorical)

weights

Optional survey weights for population-representative results

...

Additional arguments (currently unused)

Details

Understanding the Results

P-value: If p < 0.05, the variables are likely related (not independent)

Unlike the chi-square test which uses a large-sample approximation, Fisher's exact test computes the exact probability of observing the given table (or a more extreme one) under the null hypothesis of independence.

For tables larger than 2x2, the Fisher-Freeman-Halton extension is used.

When to Use This

Use Fisher's exact test when:

Relationship to Other Tests

SPSS Equivalent

SPSS: CROSSTABS /STATISTICS=CHISQ (Fisher's exact test is automatically reported for 2x2 tables)

Value

Test results showing whether two categorical variables are related, including:

References

Fisher, R. A. (1922). On the interpretation of chi-square from contingency tables, and the calculation of P. Journal of the Royal Statistical Society, 85(1), 87-94.

Freeman, G. H., & Halton, J. H. (1951). Note on an exact treatment of contingency, goodness of fit and other problems of significance. Biometrika, 38(1/2), 141-149.

See Also

chi_square for chi-square test of independence (large samples).

mcnemar_test for paired proportions.

Other hypothesis_tests: ancova(), binomial_test(), chi_square(), chisq_gof(), factorial_anova(), friedman_test(), kruskal_wallis(), mann_whitney(), mcnemar_test(), oneway_anova(), t_test(), wilcoxon_test()

Examples

# Load required packages and data
library(dplyr)
data(survey_data)

# Basic 2x2 Fisher test
survey_data %>%
  fisher_test(row = gender, col = region)

# Fisher test for larger table
survey_data %>%
  fisher_test(row = gender, col = interview_mode)

# With weights
survey_data %>%
  fisher_test(row = gender, col = region, weights = sampling_weight)

# Grouped analysis
survey_data %>%
  group_by(education) %>%
  fisher_test(row = gender, col = region)


Count How Many People Chose Each Option

Description

frequency() helps you understand categorical data by showing how many people chose each option. It's perfect for survey questions with fixed choices like education level, yes/no questions, or rating scales.

Think of it as creating a summary table that shows:

Usage

frequency(
  data,
  ...,
  weights = NULL,
  sort_frq = "none",
  show_na = TRUE,
  show_prc = TRUE,
  show_valid = TRUE,
  show_sum = TRUE,
  show_labels = "auto",
  show_unused = FALSE,
  sort.frq = NULL,
  show.na = NULL,
  show.prc = NULL,
  show.valid = NULL,
  show.sum = NULL,
  show.labels = NULL,
  show.unused = NULL
)

fre(data, ..., weights = NULL, sort_frq = "none", show_na = TRUE,
  show_prc = TRUE, show_valid = TRUE, show_sum = TRUE, show_labels = "auto",
  show_unused = FALSE, sort.frq = NULL, show.na = NULL, show.prc = NULL,
  show.valid = NULL, show.sum = NULL, show.labels = NULL, show.unused = NULL)

Arguments

data

Your survey data (a data frame or tibble)

...

The categorical variables you want to analyze. You can list multiple variables separated by commas, or use helpers like starts_with("trust")

weights

Optional survey weights for population-representative results. Without weights, you get sample frequencies. With weights, you get population estimates.

sort_frq

How to order the results:

  • "none" (default): Keep original order

  • "asc": Sort from lowest to highest frequency

  • "desc": Sort from highest to lowest frequency

show_na

Include missing values in the table? (Default: TRUE)

show_prc

Show raw percentages including missing values? (Default: TRUE)

show_valid

Show percentages excluding missing values? (Default: TRUE)

show_sum

Show cumulative totals? (Default: TRUE)

show_labels

Show category labels if available? (Default: "auto" - shows labels when they exist)

show_unused

Show all defined value labels, even those with zero observations? (Default: FALSE). When TRUE, values that have labels defined (e.g., from statistical software files) but no cases in the data are included with frequency 0. This is useful for labelled datasets where unused categories should still appear in the output. Automatically enables label display.

sort.frq, show.na, show.prc, show.valid, show.sum, show.labels, show.unused

Defunct dot-case argument names, removed in mariposa 0.6.9. Calling the function with any of them is an error; use the snake_case equivalents instead. (The formals are retained only so that the old names error clearly instead of being swallowed by ....)

Details

Understanding the Results

The frequency table shows:

When to Use This

Use frequency() when you have:

Weights Make a Difference

Without weights, you're describing your sample. With weights, you're estimating population values. Always use weights for population inference.

Tagged Missing Values

When data is imported with tagged NAs (e.g., via read_spss() with tag_na = TRUE, or read_stata(), read_sas(), read_xpt() with the tag_na parameter), frequency() automatically expands the missing value section to show each missing type individually (with its original missing value code and label), plus summary rows for Total Valid and Total Missing.

Value

A frequency table showing counts and percentages for each category

See Also

table for base R frequency tables.

crosstab for cross-tabulation of two variables.

chi_square for testing relationships between categories.

describe for numeric variable summaries.

Other descriptive: crosstab(), describe(), multiple_response(), normality_test()

Examples

# Load required packages and data
library(dplyr)
data(survey_data)

# Basic categorical analysis
survey_data %>% frequency(gender)

# Multiple variables with weights
survey_data %>% frequency(gender, region, weights = sampling_weight)

# Grouped analysis by region
survey_data %>% 
  group_by(region) %>% 
  frequency(gender, weights = sampling_weight)

# Education levels with sorting
survey_data %>% frequency(education, sort_frq = "desc")

# Employment status with custom display options
survey_data %>% frequency(employment, weights = sampling_weight, 
                         show_na = TRUE, show_sum = TRUE)


Compare Three or More Related Measurements Without Assuming Normality

Description

friedman_test() compares three or more related measurements from the same subjects when your data isn't normally distributed. It's the non-parametric alternative to repeated-measures ANOVA.

Think of it as:

The test tells you:

Usage

friedman_test(data, ..., weights = NULL, conf.level = 0.95)

Arguments

data

Your survey data (a data frame or tibble) in wide format, with one row per subject and each measurement in a separate column

...

The measurement variables to compare (at least 3). You can list them individually or use helpers like starts_with("trust_")

weights

Optional survey weights for population-representative results

conf.level

Confidence level for intervals (Default: 0.95 = 95 percent)

Details

Understanding the Results

P-value: If p < 0.05, at least one measurement is significantly different

Kendall's W (Effect size: How consistent is the pattern?):

Mean Ranks:

When to Use This

Use the Friedman test when:

Relationship to Other Tests

Weighted variants

SPSS NPAR TESTS ignores WEIGHT BY, so weighted results have no SPSS reference. The weighted variant is an R-only frequency-weight extension that reduces exactly to the unweighted test when all weights equal 1 (enforced by an internal invariance suite); see vignette("spss-compatibility") for validation status.

Value

Test results showing whether the measurements differ, including:

References

Friedman, M. (1937). The use of ranks to avoid the assumption of normality implicit in the analysis of variance. Journal of the American Statistical Association, 32(200), 675-701.

Kendall, M. G., & Babington Smith, B. (1939). The problem of m rankings. The Annals of Mathematical Statistics, 10(3), 275-287.

See Also

friedman.test for the base R Friedman test.

wilcoxon_test for comparing two related measurements.

kruskal_wallis for comparing independent groups.

Other hypothesis_tests: ancova(), binomial_test(), chi_square(), chisq_gof(), factorial_anova(), fisher_test(), kruskal_wallis(), mann_whitney(), mcnemar_test(), oneway_anova(), t_test(), wilcoxon_test()

Examples

# Load required packages and data
library(dplyr)
data(survey_data)

# Compare three trust items (rated by same respondents)
survey_data %>%
  friedman_test(trust_government, trust_media, trust_science)

# Using tidyselect helpers
survey_data %>%
  friedman_test(starts_with("trust_"))

# Weighted analysis
survey_data %>%
  friedman_test(trust_government, trust_media, trust_science,
                weights = sampling_weight)

# Grouped analysis (separate test per region)
survey_data %>%
  group_by(region) %>%
  friedman_test(trust_government, trust_media, trust_science)


Kendall's Tau Correlation Analysis

Description

Calculates Kendall's tau-b rank correlation coefficients between variables with support for weighted correlations, grouped data, and multiple variable pairs. Provides significance testing and SPSS-compatible output formatting.

The function computes tau-b, which is adjusted for ties and is particularly suitable for ordinal data or when the assumptions of Pearson correlation are not met. For weighted correlations, it uses survey-weighted rank calculations.

Usage

kendall_tau(
  data,
  ...,
  weights = NULL,
  alternative = c("two.sided", "less", "greater"),
  use = c("pairwise", "listwise"),
  na.rm = NULL
)

Arguments

data

Your survey data (a data frame or tibble)

...

The variables you want to correlate. List two for a single correlation or more for a correlation matrix. You can use helpers like starts_with("trust").

weights

Optional survey weights for population-representative results.

alternative

Direction of the test:

  • "two.sided" (default): Two-tailed test

  • "less": One-tailed test (negative correlation)

  • "greater": One-tailed test (positive correlation)

use

How to handle missing values:

  • "pairwise" (default): Pairwise deletion - each correlation uses all available cases

  • "listwise": Listwise deletion - only complete cases across all variables

na.rm

Deprecated. Use use instead.

Details

Understanding the Results

Kendall's tau measures how often pairs of observations are in the same order (concordant) versus different order (discordant). It is particularly useful for ordinal data, data with outliers, small sample sizes, and non-linear but monotonic relationships.

The tau value ranges from -1 to +1:

The output also provides:

When to Use This

Choose Kendall's tau when:

Weighted variants

The weighted tau-b is an exact frequency-weighted computation (it reproduces the unweighted tau when all weights equal 1, enforced by an internal invariance suite), but its z statistic and p-value use a no-ties normal approximation. SPSS NONPAR CORR ignores WEIGHT BY, so weighted results have no SPSS reference; see vignette("spss-compatibility") for validation status.

Value

Correlation results showing rank-based relationships between variables, including the tau-b coefficient, p-value, z-score, and sample size for each pair. For multiple variables, correlation, significance, and sample size matrices are also provided. Use summary() for the full SPSS-style output with toggleable sections.

References

Kendall, M. G. (1938). A new measure of rank correlation. Biometrika, 30(1/2), 81–93.

Kendall, M. G. (1945). The treatment of ties in ranking problems. Biometrika, 33(3), 239–251.

Agresti, A. (2010). Analysis of Ordinal Categorical Data (2nd ed.). John Wiley & Sons.

See Also

cor with method = "kendall" for the base R implementation.

spearman_rho for Spearman's rank correlation.

pearson_cor for Pearson correlation analysis.

summary.kendall_tau for detailed output with toggleable sections.

Other correlation: partial_cor(), pearson_cor(), spearman_rho()

Examples

# Load required packages and data
library(dplyr)
data(survey_data)

# Kendall's tau is O(n^2); the examples run on a subset for speed.
# On your own data, simply drop the subsetting.
mini_survey <- survey_data[1:300, ]

# Basic correlation between two variables
mini_survey %>%
  kendall_tau(life_satisfaction, political_orientation)

# Correlation matrix for multiple variables
mini_survey %>%
  kendall_tau(life_satisfaction, political_orientation, trust_media)

# Weighted correlations
mini_survey %>%
  kendall_tau(age, income, weights = sampling_weight)

# Listwise deletion for missing data
mini_survey %>%
  kendall_tau(age, income, use = "listwise")

# One-tailed test
mini_survey %>%
  kendall_tau(age, income, alternative = "greater")


# Grouped correlations
mini_survey %>%
  group_by(region) %>%
  kendall_tau(age, income, life_satisfaction)

# Using tidyselect helpers for ordinal variables
mini_survey %>%
  kendall_tau(starts_with("trust"), weights = sampling_weight)

# --- Three-layer output ---
result <- mini_survey %>%
  kendall_tau(life_satisfaction, political_orientation, trust_media,
              weights = sampling_weight)
result              # compact one-line overview
summary(result)     # full correlation, p-value, and N matrices
summary(result, pvalue_matrix = FALSE)  # hide p-values



Compare Multiple Groups Without Assuming Normal Data

Description

kruskal_wallis() compares three or more groups when your data isn't normally distributed or when you have ordinal data (like ratings or rankings). It's the non-parametric alternative to one-way ANOVA.

Think of it as:

The test tells you:

Usage

kruskal_wallis(data, ..., group, weights = NULL, conf.level = 0.95)

Arguments

data

Your survey data (a data frame or tibble)

...

The variables you want to compare between groups. You can list multiple variables or use helpers like starts_with("satisfaction")

group

The categorical variable that defines your groups (e.g., education, employment). Must have at least 2 groups (3+ for meaningful use).

weights

Optional survey weights for population-representative results

conf.level

Confidence level for intervals (Default: 0.95 = 95%)

Details

Understanding the Results

P-value: If p < 0.05, at least one group is significantly different

Effect Size Epsilon-squared (How much do groups matter?):

Mean Ranks:

When to Use This

Use Kruskal-Wallis test when:

What Comes Next?

If the Kruskal-Wallis test is significant:

  1. Look at mean ranks to see the pattern

  2. Use pairwise Mann-Whitney tests with Bonferroni correction to find which specific groups differ

  3. Consider effect sizes to judge practical importance

Relationship to Other Tests

Weighted variants

SPSS NPAR TESTS ignores WEIGHT BY, so weighted results have no SPSS reference. The weighted variant is an R-only frequency-weight extension that reduces exactly to the unweighted test when all weights equal 1 (enforced by an internal invariance suite); see vignette("spss-compatibility") for validation status.

Value

Test results showing whether groups differ, including:

References

Kruskal, W. H., & Wallis, W. A. (1952). Use of ranks in one-criterion variance analysis. Journal of the American Statistical Association, 47(260), 583-621.

Tomczak, M., & Tomczak, E. (2014). The need to report effect size estimates revisited. An overview of some recommended measures of effect size. Trends in Sport Sciences, 1(21), 19-25.

See Also

kruskal.test for the base R Kruskal-Wallis test.

mann_whitney for comparing exactly two groups.

oneway_anova for parametric one-way ANOVA.

Other hypothesis_tests: ancova(), binomial_test(), chi_square(), chisq_gof(), factorial_anova(), fisher_test(), friedman_test(), mann_whitney(), mcnemar_test(), oneway_anova(), t_test(), wilcoxon_test()

Examples

# Load required packages and data
library(dplyr)
data(survey_data)

# Basic Kruskal-Wallis test (comparing across education levels)
survey_data %>%
  kruskal_wallis(life_satisfaction, group = education)

# Multiple variables
survey_data %>%
  kruskal_wallis(life_satisfaction, income, trust_government,
                 group = education)

# Using tidyselect helpers
survey_data %>%
  kruskal_wallis(starts_with("trust_"), group = education)

# Weighted analysis
survey_data %>%
  kruskal_wallis(life_satisfaction, group = education,
                 weights = sampling_weight)

# Grouped analysis (separate test for each region)
survey_data %>%
  group_by(region) %>%
  kruskal_wallis(life_satisfaction, group = education)

# Compare across employment status (5 groups)
survey_data %>%
  kruskal_wallis(income, group = employment)


Test If Groups Vary Similarly

Description

levene_test() checks if different groups have similar amounts of variation. This is an important assumption for many statistical tests - groups should spread out in similar ways.

The test tells you:

Usage

levene_test(x, ...)

## Default S3 method:
levene_test(x, ...)

## S3 method for class 'data.frame'
levene_test(x, ..., group, weights = NULL, center = c("mean", "median"))

## S3 method for class 'oneway_anova'
levene_test(x, center = c("mean", "median"), ...)

## S3 method for class 't_test'
levene_test(x, center = c("mean", "median"), ...)

## S3 method for class 'mann_whitney'
levene_test(x, ...)

## S3 method for class 'grouped_df'
levene_test(x, variable, group = NULL, weights = NULL, center = "mean", ...)

Arguments

x

Either your data or test results from t_test() or oneway_anova()

...

Variables to test (when using data frame)

group

The grouping variable for comparison

weights

Optional survey weights for population-representative results

center

How to measure center: "mean" (default) or "median" (more robust)

variable

Variable to test (when using grouped data frame)

data

Your survey data (when x is not a test result)

Details

Understanding the Results

P-value interpretation:

Think of it like checking if all groups are equally "spread out":

When to Use This

Check variance equality when:

What If Variances Are Unequal?

If Levene's test is significant (p <= 0.05):

Usage Flexibility

You can use this function two ways:

Tips for Success

Value

Test results showing:

References

Levene, H. (1960). Robust tests for equality of variances. In I. Olkin (Ed.), Contributions to Probability and Statistics (pp. 278–292). Stanford University Press.

Brown, M. B., & Forsythe, A. B. (1974). Robust tests for the equality of variances. Journal of the American Statistical Association, 69(346), 364–367.

IBM Corp. (2023). IBM SPSS Statistics 29 Algorithms. IBM Corporation.

See Also

oneway_anova for one-way ANOVA (which assumes equal variances).

t_test for group mean comparisons.

var.test for the base R F-test of variance equality.

Other posthoc: dunn_test(), pairwise_wilcoxon(), scheffe_test(), tukey_test()

Examples

# Load required packages and data
library(dplyr)
data(survey_data)

# Standalone Levene test (test homogeneity of variances)
survey_data %>% levene_test(life_satisfaction, group = region)

# Multiple variables
survey_data %>% levene_test(life_satisfaction, trust_government, group = region)

# Weighted analysis
survey_data %>% levene_test(income, group = education, weights = sampling_weight)

# Piped after ANOVA (common workflow)
result <- survey_data %>%
  oneway_anova(life_satisfaction, group = education)
result %>% levene_test()

# Piped after t-test
survey_data %>%
  t_test(age, group = gender) %>%
  levene_test()

# Using mean instead of median as center
survey_data %>% levene_test(income, group = region, center = "mean")


Run a Linear Regression

Description

linear_regression() performs bivariate or multiple linear regression with SPSS-compatible output. Wraps stats::lm() and adds standardized coefficients (Beta), a formatted ANOVA table, and a model summary matching SPSS REGRESSION output.

Supports two interface styles:

Usage

linear_regression(
  data,
  formula = NULL,
  dependent = NULL,
  predictors = NULL,
  weights = NULL,
  use = c("listwise", "pairwise"),
  standardized = TRUE,
  conf.level = 0.95,
  factors = c("dummy", "numeric")
)

Arguments

data

Your survey data (a data frame or tibble). If grouped (via dplyr::group_by()), separate regressions are run for each group.

formula

A formula specifying the model (e.g., y ~ x1 + x2). If provided, dependent and predictors are ignored.

dependent

The dependent variable (unquoted). Used with predictors when no formula is given.

predictors

Predictor variable(s) (unquoted, supports tidyselect). Used with dependent when no formula is given.

weights

Optional survey weights (unquoted variable name). When specified, weighted least squares (WLS) is used, matching SPSS WEIGHT BY.

use

How to handle missing data: "listwise" (default) drops any case with a missing value on any variable (matching SPSS /MISSING LISTWISE). "pairwise" computes the regression from a pairwise covariance/correlation matrix, retaining more cases (matching SPSS /MISSING PAIRWISE).

standardized

Logical. If TRUE (default), standardized coefficients (Beta) are calculated and included in the output.

conf.level

Confidence level for coefficient intervals (default 0.95).

factors

How factor predictors are entered into the model: "dummy" (default, matches base R lm()) expands a factor with L levels into L - 1 contrasts; "numeric" silently coerces factor levels to their integer codes, matching SPSS REGRESSION default behavior (ordinal-as-scale). The "numeric" mode emits a one-line cli::cli_inform() listing the coerced variables. The "numeric" mode is required to reproduce SPSS results when factor predictors carry ordered meaning (e.g., 4-level education). Note that for ordered factors, "dummy" applies R's default polynomial contrasts (terms suffixed .L, .Q, .C), not treatment dummies; convert with factor(x, ordered = FALSE) first if you want dummy coding.

Details

Understanding the Results

The output includes four sections matching SPSS REGRESSION output:

Interpreting coefficients:

When to Use This

Use linear_regression() when:

For binary outcomes (yes/no, 0/1), use logistic_regression instead.

Technical Details

Missing Data: By default, listwise deletion is used (matching SPSS REGRESSION /MISSING LISTWISE). Set use = "pairwise" to match SPSS /MISSING PAIRWISE, which computes the regression from a pairwise covariance matrix. Pairwise deletion retains more cases and produces results closer to SPSS output when data has varying patterns of missingness.

Weights: When weights are specified, they are treated as frequency weights (matching SPSS WEIGHT BY behavior). The model is fitted using weighted least squares via lm(weights = ...).

Standardized Coefficients: Beta = B * (SD_x / SD_y). This matches the SPSS standardized coefficient output. Not available for the intercept. For dummy-coded factor terms (factors = "dummy"), the SD of the contrast column from the design matrix is used.

Factor Predictors: By default (factors = "dummy"), factor predictors are expanded into L - 1 contrasts via R's stats::model.matrix(), matching base R lm(): unordered factors get treatment (dummy) contrasts against the first level, while ordered factors get R's default polynomial contrasts (.L/.Q/.C terms). Pass factors = "numeric" to silently coerce factor levels to their integer codes (SPSS REGRESSION default). The "numeric" mode is required to reproduce SPSS results for ordinal predictors like education or Likert scales that SPSS treats as continuous.

Grouped Analysis: When data is grouped via dplyr::group_by(), a separate regression is run for each group (matching SPSS SPLIT FILE BY).

Value

For ungrouped + listwise data, an object of class c("linear_regression", "lm") — the fitted lm itself, with mariposa-specific slots attached:

coef_table

SPSS-style tibble with B, Std.Error, Beta, t, p, CI_lower, CI_upper. For weighted models, SE / t / p are adjusted to SPSS's frequency-weight df (see Technical Details).

anova_table

SPSS-style overall-model ANOVA tibble (Source × Sum_of_Squares / df / Mean_Square / F_statistic / Sig).

model_summary

List with R, R_squared, adj_R_squared, std_error.

descriptives

Tibble with Mean, Std.Deviation, N for all variables.

n

Sample size (listwise complete cases; weighted N when weighted).

formula, dependent, predictor_names, weighted, weight_name, use, is_grouped, standardized, conf.level

Call metadata.

Because the object inherits from "lm", all standard generics (predict(), anova(), vcov(), confint(), residuals(), fitted(), coef(), model.matrix(), broom::tidy(), broom::glance(), broom::augment()) dispatch natively without unwrapping. summary() returns the SPSS-style mariposa summary; for the raw lm summary use stats::summary.lm() on the same object.

For use = "pairwise" (no single fitted lm available) or for grouped data, returns a list of class "linear_regression". Pairwise results expose the same SPSS-style tables but not the lm generics; grouped results hold one fitted lm-inheriting model per group under $groups.

See Also

logistic_regression for binary outcome variables.

describe for checking variable distributions before regression.

pearson_cor for checking bivariate correlations.

summary.linear_regression for detailed output with toggleable sections.

Other regression: logistic_regression(), marginal_effects()

Examples

library(dplyr)
data(survey_data)

# Bivariate regression
linear_regression(survey_data, life_satisfaction ~ age)

# Multiple regression
linear_regression(survey_data, income ~ age + education + life_satisfaction)

# SPSS-style interface
linear_regression(survey_data,
                  dependent = life_satisfaction,
                  predictors = c(trust_government, trust_media, trust_science))

# Weighted regression
linear_regression(survey_data, life_satisfaction ~ age, weights = sampling_weight)

# Grouped by region
survey_data |>
  dplyr::group_by(region) |>
  linear_regression(life_satisfaction ~ age)

# Factor predictors: dummy-coding (default, matches base R lm())
linear_regression(survey_data, income ~ age + education)

# Factor predictors: SPSS-style ordinal-as-scale
linear_regression(survey_data, income ~ age + education,
                  factors = "numeric")

# --- Three-layer output ---
result <- linear_regression(survey_data, life_satisfaction ~ age + income)
result                                  # compact one-line overview
summary(result)                         # full detailed SPSS-style output
summary(result, descriptives = FALSE)   # hide descriptives section


Run a Logistic Regression

Description

logistic_regression() performs binary logistic regression with SPSS-compatible output. Wraps stats::glm(family = binomial) and adds odds ratios, pseudo R-squared measures, classification table, and model tests matching SPSS LOGISTIC REGRESSION output.

Supports two interface styles:

Usage

logistic_regression(
  data,
  formula = NULL,
  dependent = NULL,
  predictors = NULL,
  weights = NULL,
  conf.level = 0.95,
  factors = c("dummy", "numeric")
)

Arguments

data

Your survey data (a data frame or tibble). If grouped (via dplyr::group_by()), separate regressions are run for each group.

formula

A formula specifying the model (e.g., y ~ x1 + x2). If provided, dependent and predictors are ignored.

dependent

The dependent variable (unquoted). Used with predictors when no formula is given. Must be binary (0/1 or two-level factor).

predictors

Predictor variable(s) (unquoted, supports tidyselect). Used with dependent when no formula is given.

weights

Optional survey weights (unquoted variable name). When specified, weighted maximum likelihood estimation is used, matching SPSS WEIGHT BY behavior.

conf.level

Confidence level for odds ratio intervals (default 0.95).

factors

How factor predictors are entered into the model: "dummy" (default, matches base R glm()) expands a factor with L levels into L - 1 contrasts; "numeric" silently coerces factor levels to their integer codes, matching SPSS LOGISTIC REGRESSION default behavior when no /CATEGORICAL subcommand is given. The "numeric" mode emits a one-line cli::cli_inform() listing the coerced variables. Note that for ordered factors, "dummy" applies R's default polynomial contrasts (terms suffixed .L, .Q, .C), not treatment dummies; convert with factor(x, ordered = FALSE) first if you want dummy coding.

Details

Understanding the Results

The output includes five sections matching SPSS LOGISTIC REGRESSION output:

Interpreting odds ratios (Exp(B)):

When to Use This

Use logistic_regression() when:

For continuous outcomes, use linear_regression instead.

Technical Details

Dependent Variable: Must be binary. Factors with exactly 2 levels are automatically converted to 0/1 (first level = 0, second level = 1). Numeric variables must contain only 0 and 1 values.

Missing Data: Listwise deletion is used (matching SPSS LOGISTIC REGRESSION default behavior).

Weights: When weights are specified, they are treated as frequency weights (matching SPSS WEIGHT BY behavior).

Pseudo R-squared: Three measures are reported:

Factor Predictors: By default (factors = "dummy"), factor predictors are expanded into L - 1 contrasts via R's stats::model.matrix(), matching base R glm(): unordered factors get treatment (dummy) contrasts against the first level, while ordered factors get R's default polynomial contrasts (.L/.Q/.C terms). Pass factors = "numeric" to silently coerce factor levels to their integer codes (SPSS LOGISTIC REGRESSION default without an explicit /CATEGORICAL subcommand).

Grouped Analysis: When data is grouped via dplyr::group_by(), a separate regression is run for each group (matching SPSS SPLIT FILE BY).

Value

For ungrouped data, an object of class c("logistic_regression", "glm", "lm") — the fitted glm itself, with mariposa-specific slots attached:

coef_table

Tibble with B, S.E., Wald, df, Sig., Exp(B), CI_lower, CI_upper

model_summary

List with minus2LL, cox_snell_r2, nagelkerke_r2, mcfadden_r2

omnibus_test

List with chi_sq, df, p for overall model test

classification

List with table, overall_pct, pct_correct_0, pct_correct_1

hosmer_lemeshow

List with chi_sq, df, p (goodness-of-fit test)

n

Sample size (listwise complete cases; weighted N when weighted)

formula, dependent, predictor_names, weighted, weight_name, is_grouped, conf.level

Call metadata.

Because the object inherits from "glm", all standard generics (predict(), anova(), vcov(), confint(), residuals(), fitted(), coef(), broom::tidy(), broom::glance(), broom::augment()) dispatch natively without unwrapping. summary() returns the SPSS-style mariposa summary; for the raw glm summary use stats::summary.glm() on the same object.

For grouped data, returns a list of class "logistic_regression" with $groups holding one fitted glm-inheriting result per group.

See Also

linear_regression for continuous outcome variables.

chi_square for testing associations between categorical variables.

summary.logistic_regression for detailed output with toggleable sections.

Other regression: linear_regression(), marginal_effects()

Examples

library(dplyr)
data(survey_data)

# Create binary DV
survey_data$high_satisfaction <- ifelse(survey_data$life_satisfaction >= 4, 1, 0)

# Bivariate logistic regression
logistic_regression(survey_data, high_satisfaction ~ age)

# Multiple logistic regression
logistic_regression(survey_data, high_satisfaction ~ age + income + education)

# SPSS-style interface
logistic_regression(survey_data,
                    dependent = high_satisfaction,
                    predictors = c(age, income))

# Weighted logistic regression
logistic_regression(survey_data, high_satisfaction ~ age,
                    weights = sampling_weight)

# Grouped by region
survey_data |>
  dplyr::group_by(region) |>
  logistic_regression(high_satisfaction ~ age)

# Factor predictors: dummy-coding (default, matches base R glm())
logistic_regression(survey_data, high_satisfaction ~ age + education)

# Factor predictors: SPSS-style ordinal-as-scale
logistic_regression(survey_data, high_satisfaction ~ age + education,
                    factors = "numeric")

# --- Three-layer output ---
result <- logistic_regression(survey_data, high_satisfaction ~ age + income)
result                                    # compact one-line overview
summary(result)                           # full detailed SPSS-style output
summary(result, classification = FALSE)   # hide classification table


Longitudinal Study Data (Synthetic)

Description

A synthetic repeated measures dataset suitable for testing longitudinal analysis functions. Contains realistic treatment effects, missing data patterns, and within-subject correlations.

Usage

longitudinal_data

Format

A data frame with 480 rows and 10 variables:

subject_id

Subject identifier (factor, 1-120)

group

Treatment group (Control, Treatment)

age

Age in years (numeric)

gender

Gender (Male, Female)

time

Time point (T1, T2, T3, T4)

time_numeric

Time point as numeric (1-4)

outcome_score

Primary outcome measure (continuous)

secondary_outcome

Secondary outcome measure (continuous)

physio_measure

Physiological measure (continuous)

questionnaire_score

Questionnaire rating (ordered factor, 1-7)

Details

Study design features:

Missing data patterns reflect realistic longitudinal study attrition with higher dropout in later time points. The treatment effect demonstrates a clear Group x Time interaction suitable for repeated measures testing.

Source

Generated synthetically with realistic longitudinal correlation patterns and treatment effects. No real study data was used.

See Also

longitudinal_data_wide for the wide format version.

survey_data for the cross-sectional survey dataset.

Examples

# Load required packages and data
library(dplyr)
data(longitudinal_data)

# Simple example analysis with wide format data
# data(longitudinal_data_wide)
# (Repeated measures functions coming in future version)

# Descriptive statistics by group and time
longitudinal_data %>%
  group_by(group, time) %>%
  describe(outcome_score)


Longitudinal Study Data - Wide Format (Synthetic)

Description

Wide format version of the longitudinal_data dataset with one row per subject and separate columns for each time point. Useful for certain repeated measures analyses and data visualization.

Usage

longitudinal_data_wide

Format

A data frame with 120 rows and 8 variables:

subject_id

Subject identifier (factor, 1-120)

group

Treatment group (Control, Treatment)

age

Age in years (numeric)

gender

Gender (Male, Female)

score_T1

Outcome score at Time 1

score_T2

Outcome score at Time 2

score_T3

Outcome score at Time 3

score_T4

Outcome score at Time 4

Details

This is the wide format version of longitudinal_data with outcome scores spread across columns by time point. Missing values represent subject dropout or missed assessments.

Source

Generated synthetically from the long format longitudinal_data.

See Also

longitudinal_data for the long format version

Examples

# Load required packages and data
library(dplyr)
data(longitudinal_data_wide)

# Analysis of change scores
# (Repeated measures functions coming in future version)


Compare Two Groups Without Assuming Normal Data

Description

mann_whitney() compares two groups when your data isn't normally distributed or when you have ordinal data (like ratings or rankings). It's the go-to alternative when t-tests aren't appropriate.

Think of it as:

The test tells you:

Usage

mann_whitney(
  data,
  ...,
  group,
  weights = NULL,
  mu = 0,
  alternative = c("two.sided", "less", "greater"),
  conf.level = 0.95
)

Arguments

data

Your survey data (a data frame or tibble)

...

The variables you want to compare between groups. You can list multiple variables or use helpers like starts_with("satisfaction")

group

The categorical variable that defines your two groups (e.g., gender, treatment/control). Must have exactly two groups.

weights

Optional survey weights for population-representative results

mu

The hypothesized difference (Default: 0, meaning no difference)

alternative

Direction of the test:

  • "two.sided" (default): Test if groups are different

  • "greater": Test if group 1 > group 2

  • "less": Test if group 1 < group 2

conf.level

Confidence level for intervals (Default: 0.95 = 95%)

Details

Understanding the Results

P-value: If p < 0.05, the groups are significantly different

Effect Size r (How big is the difference?):

Rank Mean Difference:

When to Use This

Use Mann-Whitney test when:

Advantages Over t-test

Tips for Success

Weighted variants

The weighted test is the design-based Lumley-Scott (2013) rank test (Horvitz-Thompson midranks with a sandwich variance), validated against survey::svyranktest() rather than SPSS: SPSS NPAR TESTS ignores WEIGHT BY, so no SPSS reference exists for weighted results. The weighted descriptive U and W are design-based rank quantities and may differ from SPSS's expanded-data U; the Z statistic and p-value are the validated quantities.

Value

Test results showing whether groups differ, including:

References

Mann, H. B., & Whitney, D. R. (1947). On a test of whether one of two random variables is stochastically larger than the other. The Annals of Mathematical Statistics, 18(1), 50-60.

Wilcoxon, F. (1945). Individual comparisons by ranking methods. Biometrics Bulletin, 1(6), 80-83.

Lumley, T., & Scott, A. (2013). Two-sample rank tests under complex sampling. Biometrika, 100(4), 831-842.

See Also

wilcox.test for the base R Wilcoxon test function.

svyranktest for survey-weighted rank tests.

t_test for parametric t-tests.

summary.mann_whitney for detailed output with toggleable sections.

Other hypothesis_tests: ancova(), binomial_test(), chi_square(), chisq_gof(), factorial_anova(), fisher_test(), friedman_test(), kruskal_wallis(), mcnemar_test(), oneway_anova(), t_test(), wilcoxon_test()

Examples

# Load required packages and data
library(dplyr)
data(survey_data)

# Basic Mann-Whitney test (non-parametric comparison)
survey_data %>%
  mann_whitney(age, group = gender)

# Multiple variables
survey_data %>%
  mann_whitney(age, income, life_satisfaction, group = region)

# Using tidyselect helpers
survey_data %>%
  mann_whitney(starts_with("trust_"), group = gender)

# Weighted analysis
survey_data %>%
  mann_whitney(income, group = region, weights = sampling_weight)

# Grouped analysis (separate tests for each education level)
survey_data %>%
  group_by(education) %>%
  mann_whitney(life_satisfaction, group = gender)

# One-sided test
survey_data %>%
  mann_whitney(life_satisfaction, group = region, alternative = "greater")

# --- Three-layer output ---
result <- survey_data %>%
  mann_whitney(income, group = gender, weights = sampling_weight)
result              # compact one-line overview
summary(result)     # full detailed output with all sections
summary(result, effect_sizes = FALSE)  # hide effect sizes


Average Marginal Effects

Description

marginal_effects() computes average marginal effects (AMEs) for a fitted logistic_regression model — the Stata margins, dydx(*) workhorse. AMEs translate logit coefficients into the language reports actually use: percentage-point changes in the predicted probability.

For each continuous predictor, the AME is the derivative of the predicted probability with respect to that predictor, averaged over the observed sample. For each factor level, it is the average discrete change in predicted probability compared to the reference level.

Usage

marginal_effects(model, conf.level = 0.95, ...)

Arguments

model

A fitted model object. Currently implemented for logistic_regression results (ungrouped or grouped).

conf.level

Confidence level for the AME intervals (default 0.95).

...

Additional arguments (not used).

Details

Understanding the Output

An AME of 0.03 for age means: averaged over the sample, one additional year of age increases the predicted probability of the outcome by 3 percentage points. Unlike odds ratios, AMEs are directly comparable across models and across groups, which is why they are the preferred reporting style in much of the social sciences.

When to Use This

Technical Details

Continuous predictors use a centered numerical derivative of the predicted probability; factor predictors use the average discrete change against the reference level. Standard errors come from the delta method with the analytic gradient of the AME with respect to the coefficients and the model's Wald covariance matrix, matching the default in Stata's margins and R's margins package. Weighted models average with their frequency weights (unrounded, Charter §5.1); at weights == 1 the weighted AME reduces exactly to the unweighted one.

Linear regression: AMEs are not needed there — for a linear model without interactions or transformations, the unstandardized coefficient B is the marginal effect, already shown in the linear_regression coefficients table. Calling marginal_effects() on a linear_regression result says so instead of duplicating the table.

Validation: SPSS has no AME procedure, so this function is Tier 4 (Internal) under the Validation Charter — verified against the analytic logit-AME formula and an independent finite-difference delta-method recomputation, not against SPSS output.

Value

An object of class "marginal_effects" whose $results tibble holds one row per predictor term (and group combination) with:

Term

Predictor name; factor rows read "var: level vs. ref"

Type

"dydx" (continuous derivative) or "discrete" (factor-level contrast)

AME

Average marginal effect on the probability scale

SE

Delta-method standard error

z, p_value

Wald test of the AME

CI_lower, CI_upper

Confidence interval at conf.level

See Also

logistic_regression for fitting the model.

summary.marginal_effects for detailed output.

Other regression: linear_regression(), logistic_regression()

Examples

data(survey_data)
survey_data$high_satisfaction <- as.integer(survey_data$life_satisfaction >= 4)

model <- logistic_regression(survey_data,
                             high_satisfaction ~ age + income + education)
marginal_effects(model)

# Weighted model
model_w <- logistic_regression(survey_data, high_satisfaction ~ age + income,
                               weights = sampling_weight)
marginal_effects(model_w)

# --- Three-layer output ---
ame <- marginal_effects(model)
ame                 # compact overview
summary(ame)        # full detailed output


McNemar's Test for Paired Proportions

Description

mcnemar_test() tests whether paired proportions have changed between two dichotomous measurements. Use this for before/after comparisons of categorical outcomes.

Think of it as:

The test tells you:

Usage

mcnemar_test(data, var1, var2, weights = NULL, correct = TRUE, ...)

Arguments

data

Your survey data (data frame or tibble)

var1

First dichotomous variable (0/1 or two-level factor)

var2

Second dichotomous variable (0/1 or two-level factor)

weights

Optional survey weights for population-representative results

correct

Logical, whether to apply continuity correction (default: TRUE)

...

Additional arguments (currently unused)

Details

Understanding the Results

P-value: If p < 0.05, the paired proportions are significantly different

Exact vs Asymptotic: The exact binomial p-value is more reliable for small samples. For large samples, both p-values will be very similar.

Discordant Pairs: Only pairs where the two measurements differ (b and c) contribute to the test. If b approximately equals c, there is no evidence of systematic change.

When to Use This

Use McNemar's test when:

The McNemar Statistic

For a 2x2 table with discordant cells b and c:

\chi^2 = \frac{(|b - c| - 1)^2}{b + c}

(with continuity correction)

The exact test uses a binomial test on the discordant pairs.

Relationship to Other Tests

SPSS Equivalent

SPSS: CROSSTABS /STATISTICS=MCNEMAR

Value

Test results showing whether paired proportions changed, including:

References

McNemar, Q. (1947). Note on the sampling error of the difference between correlated proportions or percentages. Psychometrika, 12(2), 153-157.

See Also

chi_square for independence tests.

wilcoxon_test for paired non-parametric tests on ordinal data.

Other hypothesis_tests: ancova(), binomial_test(), chi_square(), chisq_gof(), factorial_anova(), fisher_test(), friedman_test(), kruskal_wallis(), mann_whitney(), oneway_anova(), t_test(), wilcoxon_test()

Examples

# Load required packages and data
library(dplyr)
data(survey_data)

# Create dichotomous variables
test_data <- survey_data %>%
  mutate(
    trust_gov_high = as.integer(trust_government >= 4),
    trust_media_high = as.integer(trust_media >= 4)
  )

# McNemar test
test_data %>%
  mcnemar_test(var1 = trust_gov_high, var2 = trust_media_high)

# Grouped analysis
test_data %>%
  group_by(region) %>%
  mcnemar_test(var1 = trust_gov_high, var2 = trust_media_high)


Analyze Multiple Response Sets

Description

multiple_response() analyzes "check all that apply" survey questions — the SPSS MULT RESPONSE procedure. It takes a set of 0/1 indicator variables (one per answer option) and produces the two tables SPSS users know:

Usage

multiple_response(data, ..., by = NULL, counted = 1, weights = NULL)

Arguments

data

Your survey data (a data frame or tibble). If grouped (via dplyr::group_by()), separate tables are produced per group (SPSS SPLIT FILE).

...

The indicator variables of the set (unquoted, supports tidyselect, e.g. starts_with("info_")). Each is checked against counted.

by

Optional categorical variable (unquoted) to cross the set against (SPSS MULT RESPONSE ... BY factor).

counted

The value that counts as a mention (default 1, matching SPSS dichotomy sets with counted value 1).

weights

Optional survey weights (unquoted variable name), treated as frequency weights matching SPSS WEIGHT BY.

Details

Understanding the Output

The two percentage columns answer different questions:

Case handling

Following SPSS MULT RESPONSE, a case is valid if it has at least one non-missing indicator in the set; cases missing on all indicators are excluded and reported as missing. Within a valid case, missing indicators simply contribute no mention. With by, cases missing on the by variable are excluded too.

Technical Details

Weighted analyses count mentions and cases as unrounded sums of weights (Charter §5.1); displayed Ns are rounded. With weights == 1 the weighted table reduces exactly to the unweighted one. Only dichotomy sets (indicator + counted value) are supported; SPSS's category-range sets are not.

An SPSS v29 MULT RESPONSE reference run is pending; until it lands the counts and percentages are verified against direct hand-computation from the indicator matrix (see the SPSS compatibility vignette).

Value

An object of class "multiple_response" whose $results tibble holds one row per answer option (and group combination) with:

Option

Variable name of the option

Label

The option's variable label (falls back to the name)

n

Number of mentions (weighted sum when weighted)

pct_responses

Share of all mentions — sums to 100%

pct_cases

Share of valid cases mentioning the option — can sum above 100%

With by, $by_results additionally holds the long-form crosstab (columns by_level, Option, Label, n, pct_cases). $n_cases is the number of valid cases (at least one non-missing indicator), $n_responses the total number of mentions.

See Also

frequency for single-variable frequency tables.

crosstab for ordinary two-variable crosstabs.

summary.multiple_response for detailed output.

Other descriptive: crosstab(), describe(), frequency(), normality_test()

Examples

library(dplyr)
data(survey_data)

# Build an example set: which institutions does a respondent
# trust highly (rating of 4 or 5)?
trust <- survey_data %>%
  mutate(
    gov     = as.integer(trust_government >= 4),
    media   = as.integer(trust_media >= 4),
    science = as.integer(trust_science >= 4)
  )

# Frequencies table: % of responses vs. % of cases
multiple_response(trust, gov, media, science)

# Crossed against gender, with weights
multiple_response(trust, gov, media, science,
                  by = gender, weights = sampling_weight)

# --- Three-layer output ---
result <- multiple_response(trust, gov, media, science)
result              # compact overview
summary(result)     # full detailed output


Frequency Table of Missing Value Types

Description

Shows a breakdown of the different types of missing values in a variable that was read with read_spss(), read_stata(), read_sas(), or read_xpt() and contains tagged NAs.

Usage

na_frequencies(x)

Arguments

x

A numeric vector with tagged NAs.

Value

A data frame with columns:

tag

The tag character (e.g., a-z for Stata, A-Z for SAS, a-z/A-Z/0-9 for SPSS)

n

Number of cases with this missing type

code

The original missing value code: numeric SPSS codes (e.g., -9, -8) or native format codes (e.g., ".a" for Stata, ".A" for SAS)

label

The value label for this missing type (if available)

See Also

read_spss(), read_stata(), read_sas(), read_xpt(), untag_na(), strip_tags()

Other data-import: read_por(), read_sas(), read_spss(), read_stata(), read_xlsx(), read_xpt(), strip_tags(), untag_na()

Examples


if (requireNamespace("haven", quietly = TRUE)) {
  # Declare -9/-8 as distinct tagged missing types, then inspect them
  x <- set_na(c(1, 2, -9, 3, -8, -9), -9, -8)
  na_frequencies(x)
  #   tag n code label
  # 1   a 2   -9  <NA>
  # 2   b 1   -8  <NA>
}



Test Variables for Normality

Description

normality_test() checks whether numeric variables follow a normal distribution, producing the two tests SPSS prints in its EXAMINE "Tests of Normality" table:

Use it before a t-test, ANOVA, or Pearson correlation to check the normality assumption, together with levene_test for the equal-variances assumption.

Usage

normality_test(data, ...)

Arguments

data

Your survey data (a data frame or tibble). If grouped (via dplyr::group_by()), the tests are run separately per group — matching SPSS EXAMINE ... BY factor.

...

Variables to test (unquoted, supports tidyselect). All selected variables must be numeric.

Details

Understanding the Output

For both tests the null hypothesis is "the variable is normally distributed":

With large survey samples these tests flag even tiny, practically irrelevant deviations. Combine them with the skewness and kurtosis from describe before deciding against a parametric test.

When to Use This

If normality is clearly violated, consider the rank-based alternatives: mann_whitney, kruskal_wallis, or spearman_rho.

Technical Details

The Lilliefors-corrected p-value uses the Dallal-Wilkinson (1986) approximation, the same correction SPSS applies in EXAMINE ("Lilliefors Significance Correction"). Shapiro-Wilk uses stats::shapiro.test() and is reported for 3 <= n <= 5000, as in SPSS. Cases with missing values are excluded per variable.

Weights: normality_test() deliberately takes no weights argument. Normality checks are a diagnostic of the sample distribution, and neither Shapiro-Wilk nor the Lilliefors correction has a well-defined fractional-frequency-weight form. Run the test on the unweighted sample.

An SPSS v29 EXAMINE reference run is pending; until it lands the statistics are verified against independent R implementations of the same published formulas (see the SPSS compatibility vignette).

Value

An object of class "normality_test" whose $results tibble holds one row per variable (and group combination) with:

n

Number of valid (non-missing) cases

ks_statistic, ks_df, ks_p

Kolmogorov-Smirnov statistic with Lilliefors-corrected p-value (Dallal-Wilkinson approximation); df equals n as in SPSS

shapiro_w, shapiro_p

Shapiro-Wilk W and p-value (NA when n < 3 or n > 5000)

References

Dallal, G. E., & Wilkinson, L. (1986). An analytic approximation to the distribution of Lilliefors's test statistic for normality. The American Statistician, 40(4), 294-296.

See Also

levene_test for the equal-variances assumption.

describe for skewness and kurtosis.

summary.normality_test for detailed output.

Other descriptive: crosstab(), describe(), frequency(), multiple_response()

Examples

library(dplyr)
data(survey_data)

# Test a single variable
normality_test(survey_data, age)

# Several variables at once
normality_test(survey_data, age, income, life_satisfaction)

# Within comparison groups (SPSS: EXAMINE ... BY gender)
survey_data %>%
  group_by(gender) %>%
  normality_test(age, income)

# --- Three-layer output ---
result <- normality_test(survey_data, age, income)
result              # compact overview
summary(result)     # full SPSS-style table


Compare Multiple Groups: Are Their Averages Different?

Description

oneway_anova() helps you determine if average values differ across three or more groups. For example, does average income vary by education level? Or is customer satisfaction different across regions?

Think of it as:

The test tells you:

Usage

oneway_anova(
  data,
  ...,
  group,
  weights = NULL,
  var.equal = TRUE,
  conf.level = 0.95
)

Arguments

data

Your survey data (a data frame or tibble)

...

The numeric variables you want to analyze. You can list multiple variables or use helpers like starts_with("income")

group

The categorical variable that defines your groups (e.g., education, region, age_group). Must have at least 3 groups for ANOVA.

weights

Optional survey weights for population-representative results

var.equal

Deprecated and ignored (a warning is issued when set to FALSE). Like SPSS ONEWAY, the classical ANOVA table and Welch's robust test are always both computed and displayed.

conf.level

Confidence level for intervals (Default: 0.95 = 95%)

Details

Understanding the Results

P-value: If p < 0.05, at least one group average is different

Effect Sizes (How much do groups matter?):

When to Use This

Use ANOVA when:

Variance Assumptions

Like SPSS ONEWAY, both results are always shown for comparison:

What Comes Next?

If ANOVA is significant:

  1. Look at group means to see the pattern

  2. Use tukey_test() to find which specific groups differ

  3. Consider effect sizes to judge practical importance

Tips for Success

Value

ANOVA results showing whether groups differ, including:

References

Cohen, J. (1988). Statistical Power Analysis for the Behavioral Sciences (2nd ed.). Lawrence Erlbaum Associates.

Welch, B. L. (1951). On the comparison of several mean values: an alternative approach. Biometrika, 38(3/4), 330-336.

Olejnik, S., & Algina, J. (2003). Generalized eta and omega squared statistics: measures of effect size for some common research designs. Psychological Methods, 8(4), 434-447.

See Also

aov for the base R ANOVA function.

oneway.test for Welch's ANOVA.

tukey_test for post-hoc pairwise comparisons.

levene_test for testing homogeneity of variances.

summary.oneway_anova for detailed output with toggleable sections.

Other hypothesis_tests: ancova(), binomial_test(), chi_square(), chisq_gof(), factorial_anova(), fisher_test(), friedman_test(), kruskal_wallis(), mann_whitney(), mcnemar_test(), t_test(), wilcoxon_test()

Examples

# Load required packages and data
library(dplyr)
data(survey_data)

# Basic one-way ANOVA (comparing across education levels)
survey_data %>%
  oneway_anova(life_satisfaction, group = education)

# Multiple dependent variables
survey_data %>%
  oneway_anova(life_satisfaction, trust_government, group = education)

# Using tidyselect helpers
survey_data %>%
  oneway_anova(starts_with("trust_"), group = education)

# Weighted analysis
survey_data %>%
  oneway_anova(income, group = education, weights = sampling_weight)

# Grouped analysis (separate ANOVA for each region)
survey_data %>%
  group_by(region) %>%
  oneway_anova(life_satisfaction, group = education)

# Store results for post-hoc analysis
result <- survey_data %>%
  oneway_anova(life_satisfaction, group = education)

# Follow up with post-hoc tests
result %>% tukey_test()
result %>% levene_test()  # Check homogeneity of variances

# --- Three-layer output ---
result              # compact one-line overview
summary(result)     # full detailed output with all sections
summary(result, descriptives = FALSE)  # hide group statistics


Find Which Specific Measurements Differ After Friedman Test

Description

pairwise_wilcoxon() tells you exactly which pairs of measurements differ from each other after the Friedman test finds overall differences. It performs all pairwise Wilcoxon signed-rank tests with p-value correction.

Think of it as:

Usage

pairwise_wilcoxon(x, ...)

## Default S3 method:
pairwise_wilcoxon(x, ...)

Arguments

x

Friedman test results from friedman_test()

...

Additional arguments passed to methods. The method for friedman_test objects accepts p_adjust (character): method for adjusting p-values for multiple comparisons. Options: "bonferroni" (default, most conservative), "holm", "BH", "hochberg", "hommel", "BY", "fdr", "none".

Details

Understanding the Results

Z-Statistics: Based on the Wilcoxon signed-rank test for each pair

Adjusted P-values: Control for multiple comparisons

The Wilcoxon Signed-Rank Test

For each pair of measurements, the Wilcoxon signed-rank test:

  1. Computes differences between the two measurements

  2. Ranks the absolute differences

  3. Computes a Z-statistic based on the rank sums

  4. Uses normal approximation with tie correction

P-Value Adjustment Methods

When to Use This

Use pairwise Wilcoxon when:

Relationship to Other Tests

Weighted variants

When the parent friedman_test() result is weighted, each pairwise test uses the same frequency-weighted signed-rank formulas. SPSS NPAR TESTS ignores WEIGHT BY, so weighted results have no SPSS reference (R-only, guarded by an internal invariance suite); see vignette("spss-compatibility") for validation status.

Value

Pairwise comparison results showing:

References

Wilcoxon, F. (1945). Individual comparisons by ranking methods. Biometrics Bulletin, 1(6), 80-83.

See Also

friedman_test for performing Friedman tests.

wilcoxon_test for individual paired Wilcoxon tests.

dunn_test for post-hoc comparisons after Kruskal-Wallis.

Other posthoc: dunn_test(), levene_test(), scheffe_test(), tukey_test()

Examples

# Load required packages and data
library(dplyr)
data(survey_data)

# Perform Friedman followed by pairwise Wilcoxon post-hoc
friedman_result <- survey_data %>%
  friedman_test(trust_government, trust_media, trust_science)

# Pairwise Wilcoxon comparisons (default: Bonferroni)
friedman_result %>% pairwise_wilcoxon()

# With Holm correction (less conservative)
friedman_result %>% pairwise_wilcoxon(p_adjust = "holm")

# With Benjamini-Hochberg (controls false discovery rate)
friedman_result %>% pairwise_wilcoxon(p_adjust = "BH")

# With weights
fw_weighted <- survey_data %>%
  friedman_test(trust_government, trust_media, trust_science,
                weights = sampling_weight)

fw_weighted %>% pairwise_wilcoxon()

# Grouped analysis
fw_grouped <- survey_data %>%
  group_by(region) %>%
  friedman_test(trust_government, trust_media, trust_science)

fw_grouped %>% pairwise_wilcoxon()


Partial Correlation

Description

partial_cor() computes partial correlations between variables while controlling for one or more other variables — the SPSS PARTIAL CORR procedure (Stata: pcorr). It answers the question "how strongly are x and y related once the influence of the control variables is removed?"

Usage

partial_cor(data, ..., controls, weights = NULL)

Arguments

data

Your survey data (a data frame or tibble). If grouped (via dplyr::group_by()), separate partial correlations are computed per group (SPSS SPLIT FILE).

...

Variables to correlate (unquoted, supports tidyselect). At least two.

controls

Control variable(s) to partial out (unquoted, supports tidyselect; SPSS BY list). At least one, must not overlap with the analysis variables.

weights

Optional survey weights (unquoted variable name), treated as frequency weights matching SPSS WEIGHT BY.

Details

Understanding the Output

Comparing partial_r against zero_order_r tells you what the controls contribute:

When to Use This

For full multivariate control with several predictors, use linear_regression instead.

Technical Details

Cases are deleted listwise across the analysis and control variables (SPSS /MISSING=LISTWISE, the PARTIAL CORR default). The partial correlation is computed from the Pearson correlation matrix of all variables via the inverse of the control-variable block; the same Pearson formula as pearson_cor is used throughout, so weighted results follow the SPSS frequency-weight convention with unrounded sum(w) in df and test statistics. Significance is two-tailed (the SPSS default).

An SPSS v29 PARTIAL CORR reference run is pending; until it lands the statistics are verified against the independent residual-of-regressions characterization (see the SPSS compatibility vignette).

Value

An object of class "partial_cor" whose $correlations tibble holds one row per variable pair (and group combination) with:

partial_r

Partial correlation controlling for the controls

zero_order_r

The ordinary (zero-order) Pearson correlation of the pair, for comparison — SPSS /STATISTICS=CORR

df

Degrees of freedom, n - 2 - k with k control variables (non-integer for weighted data, Charter §5.1)

t_stat, p_value

t-test of the partial correlation (two-tailed, the SPSS default)

n

Listwise-complete sample size (rounded weighted N when weighted)

For three or more analysis variables, $matrices additionally holds the full partial-correlation matrix per group.

See Also

pearson_cor for zero-order correlations.

linear_regression for multivariate control.

summary.partial_cor for detailed output.

Other correlation: kendall_tau(), pearson_cor(), spearman_rho()

Examples

library(dplyr)
data(survey_data)

# Does the satisfaction-income correlation survive controlling for age?
partial_cor(survey_data, life_satisfaction, income, controls = age)

# Several variables, several controls
partial_cor(survey_data, trust_government, trust_media, trust_science,
            controls = c(age, political_orientation))

# Weighted (SPSS WEIGHT BY)
partial_cor(survey_data, life_satisfaction, income,
            controls = age, weights = sampling_weight)

# Grouped (SPSS SPLIT FILE)
survey_data %>%
  group_by(gender) %>%
  partial_cor(life_satisfaction, income, controls = age)

# --- Three-layer output ---
result <- partial_cor(survey_data, life_satisfaction, income, controls = age)
result              # compact overview
summary(result)     # full detailed output


Measure How Strongly Variables Are Related

Description

pearson_cor() shows you how strongly numeric variables are related to each other. For example, is age related to income? Does satisfaction increase with experience? This helps you understand patterns in your data.

The correlation tells you:

Usage

pearson_cor(
  data,
  ...,
  weights = NULL,
  conf.level = 0.95,
  alternative = c("two.sided", "less", "greater"),
  use = c("pairwise", "listwise"),
  na.rm = NULL
)

Arguments

data

Your survey data (a data frame or tibble)

...

The numeric variables you want to correlate. List two for a single correlation or more for a correlation matrix.

weights

Optional survey weights for population-representative results. Following SPSS CORRELATIONS, the weighted degrees of freedom use n = sum(w) (not Kish's effective sample size). This is appropriate for normalized survey weights with mean \approx 1. For raw expansion weights (e.g., summing to millions of population units), the resulting standard errors and confidence intervals will be drastically too narrow — in that case, normalize weights so that sum(w) == n, or use the survey package for design-based inference.

conf.level

Confidence level for intervals (Default: 0.95 = 95%)

alternative

Direction of the test: "two.sided" (default), "less", or "greater".

use

How to handle missing values:

  • "pairwise" (default): Use all available data for each pair

  • "listwise": Only use complete cases across all variables

na.rm

Deprecated. Use use instead.

Details

Understanding the Results

Correlation coefficient (r) ranges from -1 to +1:

Interpreting strength (absolute value of r):

P-value interpretation:

A correlation of 0.65 with p < 0.001 means:

When to Use This

Use Pearson correlation when:

Don't use when:

Tips for Success

Value

Correlation results showing relationships between variables, including:

References

Cohen, J. (1988). Statistical Power Analysis for the Behavioral Sciences (2nd ed.). Lawrence Erlbaum Associates.

Fisher, R. A. (1915). Frequency distribution of the values of the correlation coefficient in samples from an indefinitely large population. Biometrika, 10(4), 507–521.

See Also

cor for the base R correlation function.

cor.test for correlation significance testing.

spearman_rho for rank-based correlation (robust to outliers).

kendall_tau for ordinal correlation.

summary.pearson_cor for detailed output with toggleable sections.

Other correlation: kendall_tau(), partial_cor(), spearman_rho()

Examples

# Load required packages and data
library(dplyr)
data(survey_data)

# Basic correlation between two variables
survey_data %>%
  pearson_cor(age, income)

# Correlation matrix for multiple variables
survey_data %>%
  pearson_cor(age, income, life_satisfaction)

# Weighted correlations
survey_data %>%
  pearson_cor(age, income, weights = sampling_weight)

# Grouped correlations
survey_data %>%
  group_by(region) %>%
  pearson_cor(age, income, life_satisfaction)

# Using tidyselect helpers
survey_data %>%
  pearson_cor(where(is.numeric), weights = sampling_weight)

# Listwise deletion for missing data
survey_data %>%
  pearson_cor(age, income, use = "listwise")

# --- Three-layer output ---
result <- survey_data %>%
  pearson_cor(age, income, life_satisfaction, weights = sampling_weight)
result              # compact one-line overview
summary(result)     # full correlation, p-value, and N matrices
summary(result, pvalue_matrix = FALSE)  # hide p-values


Effect Sizes for Contingency Tables

Description

Convenience helpers that run chi_square and return just the requested effect size as a numeric value (named by group for grouped data): phi() for 2x2 tables, cramers_v() for larger tables, and goodman_gamma() for ordinal variables.

For the full test output (chi-square statistic, p-value, all effect sizes), call chi_square directly.

Usage

phi(data, ..., weights = NULL)

cramers_v(data, ..., weights = NULL)

goodman_gamma(data, ..., weights = NULL)

Arguments

data

Your survey data (a data frame or tibble)

...

Exactly two categorical variables, as in chi_square()

weights

Optional survey weights

Value

A numeric vector with the effect size (one element per group for grouped data).

See Also

chi_square

Examples

data(survey_data)
phi(survey_data, gender, region)
cramers_v(survey_data, education, region)
goodman_gamma(survey_data, education, life_satisfaction)


Transform Scores to Percent of Maximum Possible (POMPS)

Description

pomps() transforms scores to a 0-100 scale using the Percent of Maximum Possible Scores method. This makes different scales directly comparable regardless of their original range.

This is the R equivalent of the SPSS formula: COMPUTE v81p = ((v81 - 1) / (7 - 1)) * 100.

A score of 0 means the minimum possible score, 100 means the maximum. The transformation preserves all correlations between variables.

Usage

pomps(x, scale_min = NULL, scale_max = NULL)

Arguments

x

A numeric vector to transform (e.g., a column from your data).

scale_min

The theoretical minimum of the scale. If NULL (default), the observed minimum of x is used.

scale_max

The theoretical maximum of the scale. If NULL (default), the observed maximum of x is used.

Details

The Formula

POMPS = ((score - scale_min) / (scale_max - scale_min)) * 100

Why Specify scale_min and scale_max?

By default, pomps() uses the observed minimum and maximum of your data. However, for Likert scales you should specify the theoretical range:

Using theoretical values ensures that the transformation is consistent across samples and time points.

When to Use This

Value

A numeric vector of the same length as x, with values rescaled to the 0-100 range.

See Also

row_means for creating mean indices across items.

Other scale: efa(), reliability(), row_count(), row_means(), row_sums()

Examples

library(dplyr)
data(survey_data)

# Transform a 1-5 Likert scale to POMPS
survey_data <- survey_data %>%
  mutate(trust_gov_pomps = pomps(trust_government, scale_min = 1, scale_max = 5))

# Transform multiple variables with the same scale
survey_data <- survey_data %>%
  mutate(across(
    c(trust_government, trust_media, trust_science),
    ~ pomps(.x, scale_min = 1, scale_max = 5),
    .names = "{.col}_pomps"
  ))

# Auto-detect range (uses observed min/max)
survey_data <- survey_data %>%
  mutate(age_pomps = pomps(age))


Predict from a linear_regression model

Description

For listwise + ungrouped results, dispatches to stats::predict.lm (the result inherits from "lm"). For grouped or pairwise results, raises an informative error.

Usage

## S3 method for class 'linear_regression'
predict(object, ...)

Arguments

object

A linear_regression result.

...

Passed to stats::predict.lm.

Value

A numeric vector of predictions (or a matrix/list, depending on the arguments), as returned by stats::predict.lm.


Predict from a logistic_regression model

Description

For ungrouped results, dispatches to stats::predict.glm (the result inherits from "glm"). For grouped results, raises an informative error pointing at object$groups.

Usage

## S3 method for class 'logistic_regression'
predict(object, ...)

Arguments

object

A logistic_regression result.

...

Passed to stats::predict.glm.

Value

A numeric vector of predictions on the scale requested via type (link scale by default), as returned by stats::predict.glm.


Print ANCOVA results (compact)

Description

Compact print method for objects of class "ancova". Shows factor effects and covariates with F statistics, p-values, and effect sizes.

For the full detailed output, use summary().

Usage

## S3 method for class 'ancova'
print(x, digits = 3, ...)

Arguments

x

An object of class "ancova" returned by ancova.

digits

Number of decimal places to display. Default is 3.

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

Examples

result <- ancova(survey_data, dv = life_satisfaction, between = gender, covariate = age)
result              # compact overview
summary(result)     # full detailed output


Print binomial test results (compact)

Description

Compact print method for objects of class "binomial_test". Shows a one-line summary per variable with the observed vs. test proportion, p-value, and sample size.

For the full detailed output (category table, test statistics with confidence interval), use summary().

Usage

## S3 method for class 'binomial_test'
print(x, digits = 3, ...)

Arguments

x

A binomial_test object

digits

Number of decimal places to display (default: 3)

...

Additional arguments (not used)

Value

Invisibly returns the input object x.

Examples

result <- binomial_test(survey_data, gender, p = 0.50)
result              # compact one-line overview
summary(result)     # full detailed output


Print chi-squared test results (compact)

Description

Compact print method for objects of class "chi_square". Shows a one-line summary per test with test statistic, p-value, effect size, and sample size.

For the full detailed output, use summary().

Usage

## S3 method for class 'chi_square'
print(x, digits = 3, ...)

Arguments

x

An object of class "chi_square" returned by chi_square.

digits

Number of decimal places to display. Default is 3.

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

Examples

result <- chi_square(survey_data, gender, education)
result              # compact one-line overview
summary(result)     # full detailed output


Print chi-square goodness-of-fit test results (compact)

Description

Compact print method for objects of class "chisq_gof". Shows a one-line summary per variable with the chi-square statistic, degrees of freedom, p-value, and sample size.

For the full detailed output (frequency tables with observed, expected, and residual counts), use summary().

Usage

## S3 method for class 'chisq_gof'
print(x, digits = 3, ...)

Arguments

x

An object of class "chisq_gof"

digits

Number of decimal places (default: 3)

...

Additional arguments (currently unused)

Value

Invisibly returns the input object x.

Examples

result <- chisq_gof(survey_data, gender)
result              # compact one-line overview
summary(result)     # full detailed output


Print a Compact Console Overview of the Codebook

Description

Displays a concise one-line-per-variable table in the console, showing position, name, type, and label. The full HTML codebook with values, value labels, and frequencies is displayed in the RStudio Viewer.

Usage

## S3 method for class 'codebook'
print(x, ...)

Arguments

x

A codebook object from codebook()

...

Additional arguments (ignored)

Value

Invisibly returns the codebook object

Examples

data(survey_data)
cb <- codebook(survey_data)
print(cb)


Print method for crosstab results (compact)

Description

Compact print method for objects of class "crosstab". Shows the table variables, dimensions, and valid N, plus a reminder that no significance test is included.

For the full cross-tabulation table (cell counts and percentages), use summary().

Usage

## S3 method for class 'crosstab'
print(x, digits = 1, ...)

Arguments

x

A crosstab result object

digits

Number of decimal places for percentages (default: 1)

...

Additional arguments (currently unused)

Value

Invisibly returns the input object x.

Examples

result <- crosstab(survey_data, gender, region)
result              # compact overview
summary(result)     # full cross-tabulation table


Print method for describe objects

Description

Prints formatted descriptive statistics with professional layout. Automatically adjusts output based on whether analysis was weighted or unweighted. The output of describe() is a summary table by nature, so print() and summary() display the same statistics table; summary() additionally offers a statistics section toggle and a digits option.

Usage

## S3 method for class 'describe'
print(x, digits = 3, ...)

Arguments

x

A describe object

digits

Number of decimal places to display (default: 3)

...

Additional arguments (currently unused)

Value

Invisibly returns the input object x.


Print Dunn post-hoc test results (compact)

Description

Compact print method for objects of class "dunn_test". Shows one line per variable (or group combination) with the number of pairwise comparisons and how many are significant at the .05 level.

For the full comparison tables (Z-statistics, adjusted p-values), use summary().

Usage

## S3 method for class 'dunn_test'
print(x, digits = 3, ...)

Arguments

x

An object of class "dunn_test" returned by dunn_test.

digits

Number of decimal places to display (default: 3)

...

Additional arguments passed to print. Currently unused.

Value

Invisibly returns the input object x.

Examples

result <- kruskal_wallis(survey_data, life_satisfaction,
                         group = education) |> dunn_test()
result              # compact overview
summary(result)     # full comparison tables


Print EFA results (compact)

Description

Compact print method for objects of class "efa". Shows KMO value, number of factors, total variance explained, extraction method, and rotation in a concise format.

For the full detailed output including communalities, variance explained per factor, and rotated component matrices, use summary().

Usage

## S3 method for class 'efa'
print(x, digits = 3, ...)

Arguments

x

An object of class "efa" returned by efa.

digits

Number of decimal places to display. Default is 3.

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

Examples

result <- efa(survey_data, political_orientation, environmental_concern,
              life_satisfaction, trust_government, trust_media, trust_science)
result              # compact overview
summary(result)     # full detailed output


Print factorial ANOVA results (compact)

Description

Compact print method for objects of class "factorial_anova". Shows main effects and interactions with F statistics, p-values, and effect sizes.

For the full detailed output, use summary().

Usage

## S3 method for class 'factorial_anova'
print(x, digits = 3, ...)

Arguments

x

An object of class "factorial_anova" returned by factorial_anova.

digits

Number of decimal places to display. Default is 3.

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

Examples

result <- factorial_anova(survey_data,
                          dv = life_satisfaction,
                          between = c(gender, education))
result              # compact overview
summary(result)     # full detailed output


Print Fisher's exact test results (compact)

Description

Compact print method for objects of class "fisher_test". Shows a one-line summary with the exact p-value, significance stars, and sample size.

For the full detailed output (contingency table, test results), use summary().

Usage

## S3 method for class 'fisher_test'
print(x, digits = 4, ...)

Arguments

x

An object of class "fisher_test"

digits

Number of decimal places (default: 4)

...

Additional arguments (currently unused)

Value

Invisibly returns the input object x.

Examples

result <- fisher_test(survey_data, row = gender, col = region)
result              # compact one-line overview
summary(result)     # full detailed output


Print method for frequency objects (compact)

Description

Compact print method for objects of class "frequency". Shows one line per variable (and group combination) with the number of categories, the valid N, and the missing count.

For the full frequency tables (counts, percentages, cumulative percentages), use summary().

Usage

## S3 method for class 'frequency'
print(x, digits = 3, ...)

Arguments

x

An object of class "frequency"

digits

Number of decimal places to display (default: 3)

...

Additional arguments passed to print

Value

Invisibly returns the input object x.

Examples

result <- frequency(survey_data, gender)
result              # compact overview
summary(result)     # full frequency tables


Print Friedman test results (compact)

Description

Compact print method for objects of class "friedman_test". Shows a one-line summary with the chi-square statistic, p-value, Kendall's W, and sample size.

For the full detailed output (rank tables, test statistics), use summary().

Usage

## S3 method for class 'friedman_test'
print(x, digits = 3, ...)

Arguments

x

A friedman_test object

digits

Number of decimal places to display (default: 3)

...

Additional arguments (not used)

Value

Invisibly returns the input object x.

Examples

result <- friedman_test(survey_data, trust_government, trust_media,
                        trust_science)
result              # compact one-line overview
summary(result)     # full detailed output


Print Kendall's tau results (compact)

Description

Compact print method for objects of class "kendall_tau". Shows tau coefficient, p-value, and sample size per pair.

For the full detailed output including matrices, use summary().

Usage

## S3 method for class 'kendall_tau'
print(x, digits = 3, ...)

Arguments

x

An object of class "kendall_tau" returned by kendall_tau.

digits

Number of decimal places to display. Default is 3.

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

Examples

result <- kendall_tau(survey_data[1:300, ], age, life_satisfaction)
result              # compact one-line overview
summary(result)     # full correlation matrices


Print Kruskal-Wallis test results (compact)

Description

Compact print method for objects of class "kruskal_wallis". Shows a one-line summary per variable with the H statistic, p-value, effect size (epsilon-squared), and sample size.

For the full detailed output (rank tables, test statistics), use summary().

Usage

## S3 method for class 'kruskal_wallis'
print(x, digits = 3, ...)

Arguments

x

A kruskal_wallis object

digits

Number of decimal places to display (default: 3)

...

Additional arguments (not used)

Value

Invisibly returns the input object x.

Examples

result <- kruskal_wallis(survey_data, life_satisfaction, group = education)
result              # compact one-line overview
summary(result)     # full detailed output


Print Levene test results (compact)

Description

Compact print method for objects of class "levene_test". Shows a one-line summary per variable with the F statistic, degrees of freedom, p-value, and the equal/unequal variances conclusion.

For the full detailed output (results tables, interpretation, recommendation), use summary().

Usage

## S3 method for class 'levene_test'
print(x, digits = 3, ...)

Arguments

x

A levene_test object

digits

Number of decimal places to display (default: 3)

...

Additional arguments (not used)

Value

Invisibly returns the input object x.

Examples

result <- levene_test(survey_data, life_satisfaction, group = education)
result              # compact one-line overview
summary(result)     # full detailed output


Print linear regression results (compact)

Description

Compact print method for objects of class "linear_regression". Shows R-squared, adjusted R-squared, F statistic, and p-value.

For the full detailed output, use summary().

Usage

## S3 method for class 'linear_regression'
print(x, ...)

Arguments

x

An object of class "linear_regression" returned by linear_regression.

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

Examples

result <- linear_regression(survey_data, life_satisfaction ~ age + income)
result              # compact one-line overview
summary(result)     # full detailed output


Print logistic regression results (compact)

Description

Compact print method for objects of class "logistic_regression". Shows Nagelkerke R-squared, chi-squared test, and classification accuracy.

For the full detailed output, use summary().

Usage

## S3 method for class 'logistic_regression'
print(x, ...)

Arguments

x

An object of class "logistic_regression" returned by logistic_regression.

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

Examples

survey_data$high_satisfaction <- as.integer(survey_data$life_satisfaction > 3)
result <- logistic_regression(survey_data, high_satisfaction ~ age + income)
result              # compact one-line overview
summary(result)     # full detailed output


Print Mann-Whitney test results (compact)

Description

Compact print method for objects of class "mann_whitney". Shows a one-line summary per variable with test statistic, p-value, effect size, and sample size.

For the full detailed output, use summary().

Usage

## S3 method for class 'mann_whitney'
print(x, digits = 3, ...)

Arguments

x

An object of class "mann_whitney" returned by mann_whitney.

digits

Number of decimal places to display. Default is 3.

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

Examples

result <- mann_whitney(survey_data, life_satisfaction, group = gender)
result              # compact one-line overview
summary(result)     # full detailed output


Print average marginal effects (compact)

Description

Compact print method for objects of class "marginal_effects": one line per predictor with the AME on the probability scale.

Usage

## S3 method for class 'marginal_effects'
print(x, digits = 3, ...)

Arguments

x

An object of class "marginal_effects" returned by marginal_effects.

digits

Number of decimal places (default: 3).

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

Examples

survey_data$high_satisfaction <- as.integer(survey_data$life_satisfaction >= 4)
model <- logistic_regression(survey_data, high_satisfaction ~ age + income)
marginal_effects(model)


Print McNemar test results (compact)

Description

Compact print method for objects of class "mcnemar_test". Shows a one-line summary with the McNemar chi-square statistic, the asymptotic and exact p-values, and sample size.

For the full detailed output (2x2 contingency table, test results, discordant pairs), use summary().

Usage

## S3 method for class 'mcnemar_test'
print(x, digits = 3, ...)

Arguments

x

An object of class "mcnemar_test"

digits

Number of decimal places (default: 3)

...

Additional arguments (currently unused)

Value

Invisibly returns the input object x.

Examples

test_data <- transform(survey_data,
  trust_gov_high = as.integer(trust_government >= 4),
  trust_media_high = as.integer(trust_media >= 4))
result <- mcnemar_test(test_data, var1 = trust_gov_high,
                       var2 = trust_media_high)
result              # compact one-line overview
summary(result)     # full detailed output


Print multiple response results (compact)

Description

Compact print method for objects of class "multiple_response": one line per answer option with mentions and percent of cases.

Usage

## S3 method for class 'multiple_response'
print(x, digits = 1, ...)

Arguments

x

An object of class "multiple_response" returned by multiple_response.

digits

Number of decimal places for percentages (default: 1).

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

Examples

d <- survey_data
d$gov <- as.integer(d$trust_government >= 4)
d$media <- as.integer(d$trust_media >= 4)
multiple_response(d, gov, media)


Print normality test results (compact)

Description

Compact print method for objects of class "normality_test". Shows one line per variable with both test results. For grouped analyses, only the dimensions are shown — use summary() for the per-group tables.

Usage

## S3 method for class 'normality_test'
print(x, ...)

Arguments

x

An object of class "normality_test" returned by normality_test.

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

Examples

result <- normality_test(survey_data, age, income)
result              # compact overview
summary(result)     # full detailed output


Print ANOVA test results (compact)

Description

Compact print method for objects of class "oneway_anova". Shows a one-line summary per variable with F statistic, p-value, effect size, and sample size.

For the full detailed output, use summary().

Usage

## S3 method for class 'oneway_anova'
print(x, digits = 3, ...)

Arguments

x

An object of class "oneway_anova" returned by oneway_anova.

digits

Number of decimal places to display (default: 3).

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

Examples

result <- oneway_anova(survey_data, life_satisfaction,
                       group = education)
result              # compact one-line overview
summary(result)     # full detailed output


Print pairwise Wilcoxon post-hoc test results (compact)

Description

Compact print method for objects of class "pairwise_wilcoxon". Shows one line per group combination with the number of pairwise comparisons and how many are significant at the .05 level.

For the full comparison tables (Z-statistics, adjusted p-values), use summary().

Usage

## S3 method for class 'pairwise_wilcoxon'
print(x, digits = 3, ...)

Arguments

x

An object of class "pairwise_wilcoxon" returned by pairwise_wilcoxon.

digits

Number of decimal places to display (default: 3)

...

Additional arguments passed to print. Currently unused.

Value

Invisibly returns the input object x.

Examples

result <- friedman_test(survey_data, trust_government, trust_media,
                        trust_science) |> pairwise_wilcoxon()
result              # compact overview
summary(result)     # full comparison tables


Print partial correlation results (compact)

Description

Compact print method for objects of class "partial_cor": one line per variable pair with the partial correlation, p-value, and the zero-order correlation for comparison.

Usage

## S3 method for class 'partial_cor'
print(x, digits = 3, ...)

Arguments

x

An object of class "partial_cor" returned by partial_cor.

digits

Number of decimal places (default: 3).

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

Examples

result <- partial_cor(survey_data, life_satisfaction, income, controls = age)
result              # compact overview
summary(result)     # full detailed output


Print Pearson correlation results (compact)

Description

Compact print method for objects of class "pearson_cor". Shows correlation coefficient, p-value, and sample size per pair.

For the full detailed output including matrices, use summary().

Usage

## S3 method for class 'pearson_cor'
print(x, digits = 3, ...)

Arguments

x

An object of class "pearson_cor" returned by pearson_cor.

digits

Number of decimal places to display. Default is 3.

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

Examples

result <- pearson_cor(survey_data, age, life_satisfaction)
result              # compact one-line overview
summary(result)     # full correlation matrices


Print reliability results (compact)

Description

Compact print method for objects of class "reliability". Shows Cronbach's Alpha (with quality interpretation), McDonald's Omega, and item count in a single line per group.

For the full detailed output including item statistics, inter-item correlations, and item-total statistics, use summary().

Usage

## S3 method for class 'reliability'
print(x, digits = 3, ...)

Arguments

x

An object of class "reliability" returned by reliability.

digits

Number of decimal places to display. Default is 3.

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

Examples

result <- reliability(survey_data, trust_government, trust_media, trust_science)
result              # compact one-line overview
summary(result)     # full detailed output


Print Scheffe test results (compact)

Description

Compact print method for objects of class "scheffe_test". Shows one line per variable (or factor, or group combination) with the number of pairwise comparisons and how many are significant at the .05 level.

For the full comparison tables (mean differences, confidence intervals, adjusted p-values), use summary().

Usage

## S3 method for class 'scheffe_test'
print(x, digits = 3, ...)

Arguments

x

An object of class "scheffe_test" returned by scheffe_test.

digits

Number of decimal places to display (default: 3)

...

Additional arguments passed to print. Currently unused.

Value

Invisibly returns the input object x.

Examples

result <- oneway_anova(survey_data, life_satisfaction,
                       group = education) |> scheffe_test()
result              # compact overview
summary(result)     # full comparison tables


Print Spearman correlation results (compact)

Description

Compact print method for objects of class "spearman_rho". Shows rank correlation coefficient, p-value, and sample size per pair.

For the full detailed output including matrices, use summary().

Usage

## S3 method for class 'spearman_rho'
print(x, digits = 3, ...)

Arguments

x

An object of class "spearman_rho" returned by spearman_rho.

digits

Number of decimal places to display. Default is 3.

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

Examples

result <- spearman_rho(survey_data, age, life_satisfaction)
result              # compact one-line overview
summary(result)     # full correlation matrices


Print summary of ANCOVA results (detailed output)

Description

Displays the detailed SPSS-style output for an ANCOVA, with sections controlled by the boolean parameters passed to summary.ancova. Sections include the ANCOVA table with Type III sums of squares, effect sizes, estimated marginal means, and Levene's test for homogeneity of variances.

Usage

## S3 method for class 'summary.ancova'
print(x, ...)

Arguments

x

A summary.ancova object created by summary.ancova.

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

See Also

ancova for the main analysis, summary.ancova for summary options.

Examples

result <- ancova(survey_data, dv = life_satisfaction, between = gender, covariate = age)
summary(result)                          # all sections
summary(result, marginal_means = FALSE)  # hide marginal means


Print summary of binomial test results (detailed output)

Description

Displays the detailed SPSS-style output for a binomial test, with sections controlled by the boolean parameters passed to summary.binomial_test. Sections include the category table and the test statistics table with confidence interval.

Usage

## S3 method for class 'summary.binomial_test'
print(x, ...)

Arguments

x

A summary.binomial_test object created by summary.binomial_test.

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

See Also

binomial_test for the main analysis, summary.binomial_test for summary options.

Examples

result <- binomial_test(survey_data, gender, p = 0.50)
summary(result)                     # all sections
summary(result, categories = FALSE) # hide category tables


Print summary of chi-squared test results (detailed output)

Description

Displays the detailed SPSS-style output for a chi-squared test, with sections controlled by the boolean parameters passed to summary.chi_square. Sections include cross-tabulation, test results, and effect sizes (Cramer's V, Phi).

Usage

## S3 method for class 'summary.chi_square'
print(x, ...)

Arguments

x

A summary.chi_square object created by summary.chi_square.

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

See Also

chi_square for the main analysis, summary.chi_square for summary options.

Examples

result <- chi_square(survey_data, gender, education)
summary(result)                          # all sections
summary(result, cross_tabulation = FALSE) # hide crosstab


Print summary of chi-square goodness-of-fit results (detailed output)

Description

Displays the detailed output for a chi-square goodness-of-fit test, with sections controlled by the boolean parameters passed to summary.chisq_gof. Sections include per-variable frequency tables and the test statistics table.

Usage

## S3 method for class 'summary.chisq_gof'
print(x, ...)

Arguments

x

A summary.chisq_gof object created by summary.chisq_gof.

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

See Also

chisq_gof for the main analysis, summary.chisq_gof for summary options.

Examples

result <- chisq_gof(survey_data, gender)
summary(result)                          # all sections
summary(result, frequency_table = FALSE) # hide frequency tables


Print a Detailed Console Codebook Summary

Description

Renders the verbose codebook summary to the console with boolean-gated sections for overview, variable details, and value labels.

Usage

## S3 method for class 'summary.codebook'
print(x, ...)

Arguments

x

A summary.codebook object from summary.codebook()

...

Additional arguments (ignored)

Value

Invisibly returns the summary object

Examples

data(survey_data)
cb <- codebook(survey_data)
print(summary(cb))


Print summary of crosstab results (detailed output)

Description

Displays the full cross-tabulation table for a crosstab result, with sections controlled by the boolean parameters passed to summary.crosstab. For grouped analyses, a separate table is displayed for each group combination.

Usage

## S3 method for class 'summary.crosstab'
print(x, ...)

Arguments

x

A summary.crosstab object created by summary.crosstab.

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

See Also

crosstab for the main analysis, summary.crosstab for summary options.

Examples

result <- crosstab(survey_data, gender, region)
summary(result)                       # full table
summary(result, percentages = FALSE) # counts only


Print summary of describe results (detailed output)

Description

Displays the descriptive statistics table for a describe result, controlled by the boolean parameter passed to summary.describe.

Usage

## S3 method for class 'summary.describe'
print(x, ...)

Arguments

x

A summary.describe object created by summary.describe.

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

See Also

describe for the main analysis, summary.describe for summary options.

Examples

result <- describe(survey_data, age, income)
summary(result)


Print summary of Dunn post-hoc test results (detailed output)

Description

Displays the detailed output for Dunn pairwise comparisons, with sections controlled by the boolean parameters passed to summary.dunn_test. The display includes:

For grouped analyses, results are displayed separately for each group combination.

Usage

## S3 method for class 'summary.dunn_test'
print(x, ...)

Arguments

x

A summary.dunn_test object created by summary.dunn_test.

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

See Also

dunn_test for the main analysis, summary.dunn_test for summary options.

Examples

result <- kruskal_wallis(survey_data, life_satisfaction,
                         group = education) |> dunn_test()
summary(result)                       # all sections
summary(result, comparisons = FALSE)  # hide comparison tables


Print summary of EFA results (detailed output)

Description

Displays the detailed SPSS-style output for an Exploratory Factor Analysis, with sections controlled by the boolean parameters passed to summary.efa. Sections include KMO and Bartlett's test, communalities, variance explained, and rotated component/pattern matrices.

Usage

## S3 method for class 'summary.efa'
print(x, ...)

Arguments

x

A summary.efa object created by summary.efa.

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

See Also

efa for the main analysis, summary.efa for summary options.

Examples

result <- efa(survey_data, political_orientation, environmental_concern,
              life_satisfaction, trust_government, trust_media, trust_science)
summary(result)                        # all sections
summary(result, communalities = FALSE) # hide communalities


Print summary of factorial ANOVA results (detailed output)

Description

Displays the detailed SPSS-style output for a factorial ANOVA, with sections controlled by the boolean parameters passed to summary.factorial_anova. Sections include the ANOVA table with Type III sums of squares, effect sizes, estimated marginal means, and Levene's test for homogeneity of variances.

Usage

## S3 method for class 'summary.factorial_anova'
print(x, ...)

Arguments

x

A summary.factorial_anova object created by summary.factorial_anova.

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

See Also

factorial_anova for the main analysis, summary.factorial_anova for summary options.

Examples

result <- factorial_anova(survey_data,
                          dv = life_satisfaction,
                          between = c(gender, education))
summary(result)                          # all sections
summary(result, marginal_means = FALSE)  # hide marginal means


Print summary of Fisher's exact test results (detailed output)

Description

Displays the detailed output for Fisher's exact test, with sections controlled by the boolean parameters passed to summary.fisher_test. Sections include the contingency table and the test results table.

Usage

## S3 method for class 'summary.fisher_test'
print(x, ...)

Arguments

x

A summary.fisher_test object created by summary.fisher_test.

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

See Also

fisher_test for the main analysis, summary.fisher_test for summary options.

Examples

result <- fisher_test(survey_data, row = gender, col = region)
summary(result)                            # all sections
summary(result, contingency_table = FALSE) # hide contingency table


Print summary of frequency results (detailed output)

Description

Prints formatted frequency statistics with ASCII tables, with sections controlled by the boolean parameters passed to summary.frequency.

Usage

## S3 method for class 'summary.frequency'
print(x, ...)

Arguments

x

A summary.frequency object created by summary.frequency.

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

See Also

frequency for the main analysis, summary.frequency for summary options.

Examples

result <- frequency(survey_data, gender)
summary(result)                          # all sections
summary(result, frequency_table = FALSE) # only summary statistics


Print summary of Friedman test results (detailed output)

Description

Displays the detailed SPSS-style output for a Friedman test, with sections controlled by the boolean parameters passed to summary.friedman_test. Sections include the mean rank table and the test statistics table with effect size interpretation.

Usage

## S3 method for class 'summary.friedman_test'
print(x, ...)

Arguments

x

A summary.friedman_test object created by summary.friedman_test.

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

See Also

friedman_test for the main analysis, summary.friedman_test for summary options.

Examples

result <- friedman_test(survey_data, trust_government, trust_media,
                        trust_science)
summary(result)                # all sections
summary(result, ranks = FALSE) # hide rank table


Print summary of Kendall's tau correlation results (detailed output)

Description

Displays the detailed SPSS-style output for a Kendall's tau correlation, with sections controlled by the boolean parameters passed to summary.kendall_tau. Sections include the correlation matrix, p-value matrix, and sample size matrix.

Usage

## S3 method for class 'summary.kendall_tau'
print(x, ...)

Arguments

x

A summary.kendall_tau object created by summary.kendall_tau.

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

See Also

kendall_tau for the main analysis, summary.kendall_tau for summary options.

Examples

result <- kendall_tau(survey_data[1:300, ], age, life_satisfaction)
summary(result)                             # all matrices
summary(result, pvalue_matrix = FALSE)      # hide p-values


Print summary of Kruskal-Wallis test results (detailed output)

Description

Displays the detailed SPSS-style output for a Kruskal-Wallis test, with sections controlled by the boolean parameters passed to summary.kruskal_wallis. Sections include the per-group rank table and the test statistics table with effect size.

Usage

## S3 method for class 'summary.kruskal_wallis'
print(x, ...)

Arguments

x

A summary.kruskal_wallis object created by summary.kruskal_wallis.

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

See Also

kruskal_wallis for the main analysis, summary.kruskal_wallis for summary options.

Examples

result <- kruskal_wallis(survey_data, life_satisfaction, group = education)
summary(result)                # all sections
summary(result, ranks = FALSE) # hide rank tables


Print summary of Levene test results (detailed output)

Description

Displays the detailed output for Levene's test of homogeneity of variance, with sections controlled by the boolean parameters passed to summary.levene_test. Sections include the results tables, interpretation, and recommendation.

Usage

## S3 method for class 'summary.levene_test'
print(x, ...)

Arguments

x

A summary.levene_test object created by summary.levene_test.

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

See Also

levene_test for the main analysis, summary.levene_test for summary options.

Examples

result <- levene_test(survey_data, life_satisfaction, group = education)
summary(result)                          # all sections
summary(result, interpretation = FALSE)  # hide interpretation


Print summary of linear regression results (detailed output)

Description

Displays the detailed SPSS-style output for a linear regression, with sections controlled by the boolean parameters passed to summary.linear_regression. Sections include model summary (R-squared, F-test), coefficients table (B, SE, Beta, t, p), and collinearity diagnostics (Tolerance, VIF).

Usage

## S3 method for class 'summary.linear_regression'
print(x, ...)

Arguments

x

A summary.linear_regression object created by summary.linear_regression.

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

See Also

linear_regression for the main analysis, summary.linear_regression for summary options.

Examples

result <- linear_regression(survey_data, life_satisfaction ~ age + income)
summary(result)                           # all sections
summary(result, collinearity = FALSE)     # hide VIF/Tolerance


Print summary of logistic regression results (detailed output)

Description

Displays the detailed SPSS-style output for a logistic regression, with sections controlled by the boolean parameters passed to summary.logistic_regression. Sections include the omnibus test of model coefficients, model fit statistics (Nagelkerke R-squared, Hosmer-Lemeshow), classification table, and coefficients with odds ratios.

Usage

## S3 method for class 'summary.logistic_regression'
print(x, ...)

Arguments

x

A summary.logistic_regression object created by summary.logistic_regression.

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

See Also

logistic_regression for the main analysis, summary.logistic_regression for summary options.

Examples

survey_data$high_satisfaction <- as.integer(survey_data$life_satisfaction > 3)
result <- logistic_regression(survey_data, high_satisfaction ~ age + income)
summary(result)                         # all sections
summary(result, classification = FALSE) # hide classification table


Print summary of Mann-Whitney test results (detailed output)

Description

Displays the detailed SPSS-style output for a Mann-Whitney U test, with sections controlled by the boolean parameters passed to summary.mann_whitney. Sections include rank statistics, test results, and effect sizes (rank-biserial correlation).

Usage

## S3 method for class 'summary.mann_whitney'
print(x, ...)

Arguments

x

A summary.mann_whitney object created by summary.mann_whitney.

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

See Also

mann_whitney for the main analysis, summary.mann_whitney for summary options.

Examples

result <- mann_whitney(survey_data, life_satisfaction, group = gender)
summary(result)                        # all sections
summary(result, effect_sizes = FALSE)  # hide effect sizes


Print summary of average marginal effects (detailed output)

Description

Displays the detailed AME table for a marginal_effects result, per group for grouped models.

Usage

## S3 method for class 'summary.marginal_effects'
print(x, ...)

Arguments

x

A summary.marginal_effects object created by summary.marginal_effects.

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

See Also

marginal_effects for the main analysis, summary.marginal_effects for summary options.

Examples

survey_data$high_satisfaction <- as.integer(survey_data$life_satisfaction >= 4)
model <- logistic_regression(survey_data, high_satisfaction ~ age + income)
summary(marginal_effects(model))


Print summary of McNemar test results (detailed output)

Description

Displays the detailed output for a McNemar test, with sections controlled by the boolean parameters passed to summary.mcnemar_test. Sections include the 2x2 contingency table, the test results table, and the discordant pairs.

Usage

## S3 method for class 'summary.mcnemar_test'
print(x, ...)

Arguments

x

A summary.mcnemar_test object created by summary.mcnemar_test.

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

See Also

mcnemar_test for the main analysis, summary.mcnemar_test for summary options.

Examples

test_data <- transform(survey_data,
  trust_gov_high = as.integer(trust_government >= 4),
  trust_media_high = as.integer(trust_media >= 4))
result <- mcnemar_test(test_data, var1 = trust_gov_high,
                       var2 = trust_media_high)
summary(result)                            # all sections
summary(result, discordant_pairs = FALSE)  # hide discordant pairs


Print summary of multiple response results (detailed output)

Description

Displays the detailed SPSS-style MULT RESPONSE tables for a multiple_response result, per group for grouped data.

Usage

## S3 method for class 'summary.multiple_response'
print(x, ...)

Arguments

x

A summary.multiple_response object created by summary.multiple_response.

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

See Also

multiple_response for the main analysis, summary.multiple_response for summary options.

Examples

d <- survey_data
d$gov <- as.integer(d$trust_government >= 4)
d$media <- as.integer(d$trust_media >= 4)
summary(multiple_response(d, gov, media, by = gender))


Print summary of normality test results (detailed output)

Description

Displays the SPSS-style "Tests of Normality" table (Kolmogorov-Smirnov with Lilliefors correction, Shapiro-Wilk) for a normality_test result, per group for grouped data.

Usage

## S3 method for class 'summary.normality_test'
print(x, ...)

Arguments

x

A summary.normality_test object created by summary.normality_test.

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

See Also

normality_test for the main analysis, summary.normality_test for summary options.

Examples

result <- normality_test(survey_data, age, income)
summary(result)


Print summary of one-way ANOVA results (detailed output)

Description

Displays the detailed SPSS-style output for a one-way ANOVA, with sections controlled by the boolean parameters passed to summary.oneway_anova. Sections include group descriptives, ANOVA table, homogeneity of variances (Levene's test), and effect sizes.

Usage

## S3 method for class 'summary.oneway_anova'
print(x, ...)

Arguments

x

A summary.oneway_anova object created by summary.oneway_anova.

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

See Also

oneway_anova for the main analysis, summary.oneway_anova for summary options.

Examples

result <- oneway_anova(survey_data, life_satisfaction, group = education)
summary(result)                        # all sections
summary(result, descriptives = FALSE)  # hide group statistics


Print summary of pairwise Wilcoxon post-hoc test results (detailed output)

Description

Displays the detailed output for pairwise Wilcoxon comparisons, with sections controlled by the boolean parameters passed to summary.pairwise_wilcoxon. The display includes:

For grouped analyses, results are displayed separately for each group.

Usage

## S3 method for class 'summary.pairwise_wilcoxon'
print(x, ...)

Arguments

x

A summary.pairwise_wilcoxon object created by summary.pairwise_wilcoxon.

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

See Also

pairwise_wilcoxon for the main analysis, summary.pairwise_wilcoxon for summary options.

Examples

result <- friedman_test(survey_data, trust_government, trust_media,
                        trust_science) |> pairwise_wilcoxon()
summary(result)                       # all sections
summary(result, comparisons = FALSE)  # hide comparison tables


Print summary of partial correlation results (detailed output)

Description

Displays the detailed SPSS-style output for a partial_cor result, with sections controlled by the boolean parameters passed to summary.partial_cor.

Usage

## S3 method for class 'summary.partial_cor'
print(x, ...)

Arguments

x

A summary.partial_cor object created by summary.partial_cor.

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

See Also

partial_cor for the main analysis, summary.partial_cor for summary options.

Examples

result <- partial_cor(survey_data, life_satisfaction, income, controls = age)
summary(result)


Print summary of Pearson correlation results (detailed output)

Description

Displays the detailed SPSS-style output for a Pearson correlation, with sections controlled by the boolean parameters passed to summary.pearson_cor. Sections include the correlation matrix, p-value matrix, and sample size matrix.

Usage

## S3 method for class 'summary.pearson_cor'
print(x, ...)

Arguments

x

A summary.pearson_cor object created by summary.pearson_cor.

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

See Also

pearson_cor for the main analysis, summary.pearson_cor for summary options.

Examples

result <- pearson_cor(survey_data, age, life_satisfaction)
summary(result)                             # all matrices
summary(result, pvalue_matrix = FALSE)      # hide p-values


Print summary of reliability analysis results (detailed output)

Description

Displays the detailed SPSS-style output for a reliability analysis, with sections controlled by the boolean parameters passed to summary.reliability. Sections include reliability statistics, item statistics, inter-item correlations, and item-total statistics.

Usage

## S3 method for class 'summary.reliability'
print(x, ...)

Arguments

x

A summary.reliability object created by summary.reliability.

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

See Also

reliability for the main analysis, summary.reliability for summary options.

Examples

result <- reliability(survey_data, trust_government, trust_media, trust_science)
summary(result)                                  # all sections
summary(result, inter_item_correlations = FALSE)  # hide correlations


Print summary of Scheffe test results (detailed output)

Description

Displays the detailed output for Scheffe post-hoc comparisons, with sections controlled by the boolean parameters passed to summary.scheffe_test. The display includes:

For grouped analyses, results are displayed separately for each group combination. For weighted analyses, effective sample sizes are used in calculations.

Usage

## S3 method for class 'summary.scheffe_test'
print(x, ...)

Arguments

x

A summary.scheffe_test object created by summary.scheffe_test.

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

See Also

scheffe_test for the main analysis, summary.scheffe_test for summary options.

Examples

result <- oneway_anova(survey_data, life_satisfaction,
                       group = education) |> scheffe_test()
summary(result)                       # all sections
summary(result, comparisons = FALSE)  # hide comparison tables


Print summary of Spearman correlation results (detailed output)

Description

Displays the detailed SPSS-style output for a Spearman rank correlation, with sections controlled by the boolean parameters passed to summary.spearman_rho. Sections include the correlation matrix, p-value matrix, and sample size matrix.

Usage

## S3 method for class 'summary.spearman_rho'
print(x, ...)

Arguments

x

A summary.spearman_rho object created by summary.spearman_rho.

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

See Also

spearman_rho for the main analysis, summary.spearman_rho for summary options.

Examples

result <- spearman_rho(survey_data, age, life_satisfaction)
summary(result)                             # all matrices
summary(result, pvalue_matrix = FALSE)      # hide p-values


Print summary of t-test results (detailed output)

Description

Displays the detailed SPSS-style output for a t-test, with sections controlled by the boolean parameters passed to summary.t_test. Sections include group descriptives, test results (equal and unequal variances), and effect sizes.

Usage

## S3 method for class 'summary.t_test'
print(x, ...)

Arguments

x

A summary.t_test object created by summary.t_test.

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

See Also

t_test for the main analysis, summary.t_test for summary options.

Examples

result <- t_test(survey_data, life_satisfaction, group = gender)
summary(result)                        # all sections
summary(result, effect_sizes = FALSE)  # hide effect sizes


Print summary of Tukey HSD test results (detailed output)

Description

Displays the detailed output for Tukey HSD post-hoc comparisons, with sections controlled by the boolean parameters passed to summary.tukey_test. The display includes:

For grouped analyses, results are displayed separately for each group combination. For weighted analyses, effective sample sizes are used in calculations.

Usage

## S3 method for class 'summary.tukey_test'
print(x, ...)

Arguments

x

A summary.tukey_test object created by summary.tukey_test.

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

See Also

tukey_test for the main analysis, summary.tukey_test for summary options.

Examples

result <- oneway_anova(survey_data, life_satisfaction,
                       group = education) |> tukey_test()
summary(result)                     # all sections
summary(result, comparisons = FALSE)  # hide comparison tables


Print summary of Wilcoxon signed-rank test results (detailed output)

Description

Displays the detailed SPSS-style output for a Wilcoxon signed-rank test, with sections controlled by the boolean parameters passed to summary.wilcoxon_test. Sections include the rank table and the test statistics table with effect size interpretation.

Usage

## S3 method for class 'summary.wilcoxon_test'
print(x, ...)

Arguments

x

A summary.wilcoxon_test object created by summary.wilcoxon_test.

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

See Also

wilcoxon_test for the main analysis, summary.wilcoxon_test for summary options.

Examples

result <- wilcoxon_test(survey_data, x = trust_government, y = trust_media)
summary(result)                # all sections
summary(result, ranks = FALSE) # hide rank table


Print t-test results (compact)

Description

Compact print method for objects of class "t_test". Shows a one-line summary per variable with test statistic, p-value, effect size, and sample size.

For the full detailed output, use summary().

Usage

## S3 method for class 't_test'
print(x, digits = 3, ...)

Arguments

x

An object of class "t_test" returned by t_test.

digits

Number of decimal places to display. Default is 3.

...

Additional arguments (not used).

Value

Invisibly returns the input object x.

Examples

result <- t_test(survey_data, life_satisfaction, group = gender)
result              # compact one-line overview
summary(result)     # full detailed output


Print Tukey HSD test results (compact)

Description

Compact print method for objects of class "tukey_test". Shows one line per variable (or factor, or group combination) with the number of pairwise comparisons and how many are significant at the .05 level.

For the full comparison tables (mean differences, confidence intervals, adjusted p-values), use summary().

Usage

## S3 method for class 'tukey_test'
print(x, digits = 3, ...)

Arguments

x

An object of class "tukey_test" returned by tukey_test.

digits

Number of decimal places to display (default: 3)

...

Additional arguments passed to print. Currently unused.

Value

Invisibly returns the input object x.

Examples

result <- oneway_anova(survey_data, life_satisfaction,
                       group = education) |> tukey_test()
result              # compact overview
summary(result)     # full comparison tables


Print method for w_modus objects

Description

Print method for w_modus objects

Usage

## S3 method for class 'w_modus'
print(x, digits = 3, ...)

Arguments

x

A w_modus object

digits

Number of decimal places to display (default: 3)

...

Additional arguments (not used)

Value

Invisibly returns the input object x.


Print method for w_quantile objects

Description

Prints a formatted summary of weighted quantile calculations, including quantiles, sample sizes, and weights (if applicable). For grouped data, results are displayed by group.

Usage

## S3 method for class 'w_quantile'
print(x, digits = 3, ...)

Arguments

x

An object of class "w_quantile"

digits

Number of decimal places to display (default: 3)

...

Additional arguments passed to print

Value

Invisibly returns the input object x.


Print Wilcoxon signed-rank test results (compact)

Description

Compact print method for objects of class "wilcoxon_test". Shows a one-line summary per comparison with the Z statistic, p-value, effect size r, and sample size.

For the full detailed output (rank tables, test statistics), use summary().

Usage

## S3 method for class 'wilcoxon_test'
print(x, digits = 3, ...)

Arguments

x

A wilcoxon_test object

digits

Number of decimal places to display (default: 3)

...

Additional arguments (not used)

Value

Invisibly returns the input object x.

Examples

result <- wilcoxon_test(survey_data, x = trust_government, y = trust_media)
result              # compact one-line overview
summary(result)     # full detailed output


Read SPSS Portable Data with Tagged Missing Values

Description

Reads an SPSS portable .por file and preserves user-defined missing values as tagged NAs. This is the portable format equivalent of read_spss() for .sav files.

Usage

read_por(path, tag_na = TRUE, verbose = FALSE)

Arguments

path

Path to an SPSS .por file.

tag_na

If TRUE (the default), user-defined missing values are converted to tagged NAs using haven::tagged_na(). If FALSE, the file is read with standard haven::read_por() behavior.

verbose

If TRUE, prints a message summarizing how many values were converted.

Details

The SPSS portable format (.por) is an older, platform-independent format. Unlike .sav files, the portable format does not support specifying a character encoding. Tagged NA handling is identical to read_spss().

Value

A tibble with the SPSS data. See read_spss() for details on tagged NA handling.

See Also

read_spss(), na_frequencies(), untag_na(), strip_tags(), haven::read_por()

Other data-import: na_frequencies(), read_sas(), read_spss(), read_stata(), read_xlsx(), read_xpt(), strip_tags(), untag_na()

Examples


# .por files cannot be produced from R, so this only runs when one
# is present in the working directory
if (requireNamespace("haven", quietly = TRUE) &&
    file.exists("survey.por")) {
  data <- read_por("survey.por")
  na_frequencies(data$satisfaction)
}



Read SAS Data with Tagged Missing Values

Description

Reads a SAS .sas7bdat file and integrates with mariposa's tagged NA system. Handles two scenarios:

  1. Native special missing values (.A through .Z, ._): Automatically detected and annotated.

  2. Numeric missing codes (e.g., -9, -42): When tag_na is provided, these regular values are converted to tagged NAs, giving the same result as read_spss() with tag_na = TRUE.

Usage

read_sas(
  path,
  catalog_file = NULL,
  encoding = NULL,
  catalog_encoding = NULL,
  tag_na = NULL,
  verbose = FALSE
)

Arguments

path

Path to a SAS .sas7bdat data file.

catalog_file

Path to a SAS catalog file (.sas7bcat) for value labels. If NULL, no catalog is used.

encoding

Character encoding for the data file. If NULL, haven's default encoding detection is used.

catalog_encoding

Character encoding for the catalog file. If NULL, the same encoding as the data file is used.

tag_na

Numeric vector of values to treat as missing (e.g., c(-9, -8, -42)). These values will be converted to tagged NAs across all numeric variables. Use this when SAS files contain missing codes stored as regular values. Default: NULL (only detect native SAS special missing values).

verbose

If TRUE, prints a message summarizing how many variables contain tagged missing values.

Details

Native Special Missing Values

SAS supports 28 distinct missing value types: . (system missing), .A through .Z, and ._ (underscore). The haven package preserves these as tagged NAs automatically. read_sas() adds the na_tag_map attribute so that mariposa's tagged NA functions work seamlessly.

Numeric Missing Codes (tag_na)

Some SAS files store missing value codes as regular numeric values (e.g., -9 = "No answer"). The tag_na parameter converts these to tagged NAs, enabling proper handling in frequency(), codebook(), and other functions.

When tag_na is used, untag_na() can recover the original numeric codes.

Value

A tibble with the SAS data. Variables with missing value codes have:

See Also

read_xpt(), na_frequencies(), strip_tags(), untag_na(), read_spss(), read_stata(), haven::read_sas()

Other data-import: na_frequencies(), read_por(), read_spss(), read_stata(), read_xlsx(), read_xpt(), strip_tags(), untag_na()

Examples


# .sas7bdat files cannot be produced from R, so this only runs when
# one is present in the working directory
if (requireNamespace("haven", quietly = TRUE) &&
    file.exists("survey.sas7bdat")) {
  # Read SAS file with native special missing values
  data <- read_sas("survey.sas7bdat")

  # Read with catalog for value labels
  data <- read_sas("survey.sas7bdat", catalog_file = "formats.sas7bcat")

  # Read SAS file with numeric missing codes
  data <- read_sas("survey.sas7bdat", tag_na = c(-9, -8, -42))
}



Read SPSS Data with Tagged Missing Values

Description

Reads an SPSS .sav file and preserves user-defined missing values as tagged NAs instead of converting them to regular NA. This allows you to distinguish between different types of missing data (e.g., "no answer", "not applicable", "refused") while still treating them as NA in standard R operations.

Usage

read_spss(path, tag_na = TRUE, encoding = NULL, verbose = FALSE)

Arguments

path

Path to an SPSS .sav file.

tag_na

If TRUE (the default), user-defined missing values are converted to tagged NAs using haven::tagged_na(). If FALSE, the file is read with standard haven::read_sav() behavior (all missing values become regular NA).

encoding

Character encoding for the file. If NULL, haven's default encoding detection is used.

verbose

If TRUE, prints a message summarizing how many values were converted.

Details

SPSS allows defining specific values as "user-defined missing values" (e.g., -9 = "no answer", -8 = "don't know"). When reading .sav files with haven::read_sav(), these are silently converted to NA, losing the information about why a value is missing.

read_spss() preserves this information using haven's tagged NA system: each missing value type gets a unique tag character (a-z, A-Z, 0-9) that can be inspected with haven::na_tag(). The values still behave as NA in all standard R operations (mean(), sum(), is.na(), etc.).

Use the companion functions to work with the tagged NAs:

Value

A tibble with the SPSS data. When tag_na = TRUE:

See Also

na_frequencies(), untag_na(), strip_tags(), haven::read_sav(), frequency(), read_por()

Other data-import: na_frequencies(), read_por(), read_sas(), read_stata(), read_xlsx(), read_xpt(), strip_tags(), untag_na()

Examples


if (requireNamespace("haven", quietly = TRUE)) {
  # Roundtrip through a temporary .sav file (with your own data,
  # simply pass its path instead)
  tmp <- tempfile(fileext = ".sav")
  write_spss(survey_data, tmp)
  data <- read_spss(tmp)

  # Standard R operations work normally (NAs are excluded)
  mean(data$life_satisfaction, na.rm = TRUE)

  # frequency() shows each missing type separately
  data |> frequency(life_satisfaction)

  unlink(tmp)
}



Read Stata Data with Tagged Missing Values

Description

Reads a Stata .dta file and integrates with mariposa's tagged NA system. Handles two scenarios:

  1. Native extended missing values (.a through .z): Automatically detected and annotated.

  2. Numeric missing codes (e.g., -9, -42): When tag_na is provided, these regular values are converted to tagged NAs, giving the same result as read_spss() with tag_na = TRUE.

Usage

read_stata(path, encoding = NULL, tag_na = NULL, verbose = FALSE)

Arguments

path

Path to a Stata .dta file.

encoding

Character encoding for the file. If NULL, haven's default encoding detection is used. Generally only needed for Stata 13 files and earlier.

tag_na

Numeric vector of values to treat as missing (e.g., c(-9, -8, -42)). These values will be converted to tagged NAs across all numeric variables. Use this when Stata files contain SPSS-style missing codes stored as regular values. Default: NULL (only detect native Stata extended missing values).

verbose

If TRUE, prints a message summarizing how many variables contain tagged missing values.

Details

Native Extended Missing Values

Stata supports 27 distinct missing value types: . (system missing) and .a through .z (extended missing values). The haven package preserves these as tagged NAs automatically. read_stata() adds the na_tag_map attribute so that mariposa's tagged NA functions work seamlessly.

Numeric Missing Codes (tag_na)

Many Stata files – especially those converted from SPSS – store missing value codes as regular numeric values (e.g., -9 = "No answer", -42 = "Data error"). The tag_na parameter converts these to tagged NAs, enabling proper handling in frequency(), codebook(), and other functions.

When tag_na is used, untag_na() can recover the original numeric codes.

Value

A tibble with the Stata data. Variables with missing value codes have:

See Also

na_frequencies(), strip_tags(), untag_na(), read_spss(), read_sas(), read_xpt(), haven::read_dta()

Other data-import: na_frequencies(), read_por(), read_sas(), read_spss(), read_xlsx(), read_xpt(), strip_tags(), untag_na()

Examples


if (requireNamespace("haven", quietly = TRUE)) {
  # Roundtrip through a temporary .dta file (with your own data,
  # simply pass its path instead)
  tmp <- tempfile(fileext = ".dta")
  write_stata(survey_data, tmp)
  data <- read_stata(tmp)

  # Read with SPSS-style missing codes tagged as distinct NA types
  data <- read_stata(tmp, tag_na = c(-9, -8))

  # frequency() shows each missing type separately
  data |> frequency(income)

  unlink(tmp)
}



Read Excel Data with Label Reconstruction

Description

Reads an Excel (.xlsx) file and returns a tibble. When the file was created by write_xlsx(), the accompanying "Labels" sheet is automatically detected and used to reconstruct variable labels, value labels, and tagged NA metadata – giving you the same labelled structure as the original data.

For plain Excel files (without a "Labels" sheet), this function works like a convenient wrapper around the openxlsx2 reader, returning a clean tibble.

Usage

read_xlsx(path, sheet = NULL, labels = TRUE, verbose = FALSE, ...)

Arguments

path

Path to the .xlsx file.

sheet

Sheet to read. NULL (default) auto-detects: reads the "Data" sheet if present, otherwise the first non-metadata sheet. Can be a sheet name (character) or index (integer).

labels

If TRUE (default), detects a "Labels" sheet and reconstructs haven_labelled columns, factor levels, variable labels, and tagged NA metadata. Set to FALSE to read raw data without label reconstruction.

verbose

If TRUE, prints a summary of reconstructed labels and tagged NA mappings.

...

Additional arguments (currently unused).

Details

Roundtrip Workflow

read_xlsx() is designed to work seamlessly with write_xlsx():

write_xlsx(data, "survey.xlsx")   # Exports data + Labels sheet
data2 <- read_xlsx("survey.xlsx") # Reconstructs labels from Labels sheet

The reconstructed data will have the same variable labels, value labels, and tagged NA codes as the original. System NAs (empty cells in Excel) remain as regular NA.

File Format Detection

read_xlsx() auto-detects the type of mariposa export:

When to Use This

Use read_xlsx() when you:

Value

A tibble. When a mariposa-formatted Labels sheet is detected:

See Also

write_xlsx() for exporting data with labels, read_spss(), read_stata(), read_sas() for importing from statistical software

Other data-import: na_frequencies(), read_por(), read_sas(), read_spss(), read_stata(), read_xpt(), strip_tags(), untag_na()

Examples


if (requireNamespace("openxlsx2", quietly = TRUE)) {
  # Roundtrip: export with labels, read back with reconstruction
  tmp <- tempfile(fileext = ".xlsx")
  write_xlsx(survey_data, tmp)

  data <- read_xlsx(tmp)
  attr(data$gender, "labels")   # Value labels restored
  attr(data$gender, "label")    # Variable label restored

  # Skip label reconstruction
  raw <- read_xlsx(tmp, labels = FALSE)

  unlink(tmp)
}



Read SAS Transport File with Tagged Missing Values

Description

Reads a SAS transport file (.xpt) and integrates with mariposa's tagged NA system. Handles both native SAS special missing values and user-specified numeric missing codes (via tag_na). Transport files are a platform-independent SAS data format commonly used for FDA submissions and data exchange.

Usage

read_xpt(path, tag_na = NULL, verbose = FALSE)

Arguments

path

Path to a SAS transport file (.xpt).

tag_na

Numeric vector of values to treat as missing (e.g., c(-9, -8, -42)). These values will be converted to tagged NAs across all numeric variables. Default: NULL (only detect native SAS special missing values).

verbose

If TRUE, prints a message summarizing how many variables contain tagged missing values.

Details

SAS transport files support the same special missing values as .sas7bdat files (.A-.Z, ._). This format is self-contained and does not require a separate catalog file for value labels.

When tag_na is used, untag_na() can recover the original numeric codes.

Value

A tibble with the SAS data. See read_sas() for details on tagged NA handling.

See Also

read_sas(), na_frequencies(), strip_tags(), untag_na(), haven::read_xpt()

Other data-import: na_frequencies(), read_por(), read_sas(), read_spss(), read_stata(), read_xlsx(), strip_tags(), untag_na()

Examples


if (requireNamespace("haven", quietly = TRUE)) {
  # Roundtrip through a temporary .xpt transport file
  tmp <- tempfile(fileext = ".xpt")
  write_xpt(survey_data, tmp)
  data <- read_xpt(tmp)

  # Read with numeric missing codes tagged as distinct NA types
  data <- read_xpt(tmp, tag_na = c(-9, -8))

  unlink(tmp)
}



Recode Variables Using String Syntax

Description

rec() recodes values of a variable using an intuitive string syntax. It consolidates recoding, reversing, dichotomizing, and missing value handling in a single function — the R equivalent of SPSS's RECODE command.

Usage

rec(
  data,
  ...,
  rules,
  as_factor = FALSE,
  suffix = NULL,
  var_label = NULL,
  val_labels = NULL,
  as.factor = NULL,
  var.label = NULL,
  val.labels = NULL
)

Arguments

data

A data frame or numeric vector. When a data frame is passed, use ... to select variables.

...

Variables to recode (tidyselect). Only used when data is a data frame.

rules

A character string defining the recoding rules (see Details).

as_factor

If TRUE, return the result as a factor. Default: FALSE.

suffix

A character string appended to the column names for the recoded variables (e.g., "_r"). If NULL (default), the original columns are overwritten in-place.

var_label

A new variable label. If NULL, the existing label is kept with " (recoded)" appended.

val_labels

A named character vector of value labels for the new values (e.g., c("1" = "Low", "2" = "Medium", "3" = "High")). If NULL, labels are taken from inline [Label] syntax in rules (if present). Explicit val_labels always override inline labels.

as.factor, var.label, val.labels

Defunct dot-case argument names, removed in mariposa 0.6.9. Calling the function with any of them is an error; use the snake_case equivalents instead. (The formals are retained only so that the old names error clearly instead of being swallowed by ....)

Details

Recoding Syntax

Rules are specified as a semicolon-separated string of "old=new" pairs:

Syntax Meaning Example
"old=new" Single value "1=0; 2=1"
"lo:hi=new" Range of values "1:3=1; 4:6=2"
"old=new [Label]" Inline value label "1:2=1 [Low]; 3:5=2 [High]"
"else=new" Catch-all for unmatched "1=1; else=NA"
"copy" Keep original value "1:3=copy; else=NA"
"min"/"max" Dynamic boundaries "min:3=1; 4:max=2"
"rev" Reverse scale "rev"
"dicho" Median split "dicho"
"dicho(x)" Fixed cut-point "dicho(3)"
"mean" Mean split "mean"
"quart" Quartile split (4 groups) "quart"
"NA=new" Replace NA "NA=0; else=copy"
"val=NA" Set values to NA "-9=NA; -8=NA"

Rules are evaluated in order — the first matching rule wins.

Decimal Values

Both single values and ranges accept decimals (e.g. "3.6=2" or "2.5:3.5=1"). Single-value matching compares values as strings (rounded to 15 significant digits), so decimal codes match reliably even when stored with floating-point representation error.

Inline Value Labels

You can attach value labels directly in the rules string using square brackets after the new value:

"1:2=1 [Low]; 3=2 [Medium]; 4:5=3 [High]"

This is equivalent to specifying val_labels = c("1" = "Low", "2" = "Medium", "3" = "High") but more compact and self-documenting. If both inline labels and val_labels are provided, val_labels takes precedence.

Special Modes

"rev" reverses the scale by computing max(x) + min(x) - x. Value labels are mirrored accordingly.

"dicho" dichotomizes at the median: values \le median become 0, values > median become 1.

"dicho(x)" dichotomizes at a fixed cut-point x: values \le x become 0, values > x become 1.

"mean" dichotomizes at the arithmetic mean: values \le mean become 0, values > mean become 1.

"quart" splits into four quartile groups using quantile(): values \le Q1 become 1, Q1–Q2 become 2, Q2–Q3 become 3, and > Q3 become 4. Quartile boundaries are computed unweighted.

Value

If data is a vector, a recoded vector is returned. If data is a data frame, the modified data frame is returned (invisibly).

See Also

to_dummy() for creating dummy variables, set_na() for declaring missing values, to_label() for converting to factor labels

Other recode: to_dummy()

Examples

library(dplyr)
data(survey_data)

# Collapse a 5-point scale to 3 categories (inline labels)
data <- rec(survey_data, trust_government,
            rules = "1:2=1 [Low]; 3=2 [Medium]; 4:5=3 [High]")

# Reverse a scale (with suffix to keep original)
data <- rec(survey_data, trust_government, trust_media,
            rules = "rev", suffix = "_r")

# Dichotomize at the median
data <- rec(survey_data, age, rules = "dicho", suffix = "_d")

# Set missing value codes to NA
data <- rec(survey_data, starts_with("trust"),
            rules = "-9=NA; -8=NA; else=copy")

# Replace NA with 0
data <- rec(survey_data, trust_government,
            rules = "NA=0; else=copy")

# Quartile split
data <- rec(survey_data, age, rules = "quart", suffix = "_q")

# Use inside mutate()
survey_data <- survey_data %>%
  mutate(
    trust_gov_3 = rec(trust_government,
                      rules = "1:2=1 [Low]; 3=2 [Medium]; 4:5=3 [High]"),
    age_q = rec(age, rules = "quart")
  )


Check How Reliably Your Scale Measures a Concept

Description

reliability() calculates Cronbach's Alpha, McDonald's Omega, and detailed item statistics to evaluate whether your survey items form a reliable scale. This is the R equivalent of SPSS's RELIABILITY /MODEL=ALPHA /STATISTICS=DESCRIPTIVE CORR /SUMMARY=TOTAL.

For example, if you have 3 items measuring "trust", reliability analysis tells you whether these items consistently measure the same concept.

Usage

reliability(data, ..., weights = NULL, na.rm = TRUE)

Arguments

data

Your survey data (a data frame or tibble)

...

The items to analyze. Use bare column names separated by commas, or tidyselect helpers like starts_with("trust").

weights

Optional survey weights for population-representative results

na.rm

Remove missing values before calculating? (Default: TRUE). Uses listwise deletion (only complete cases across all items).

Details

Understanding the Results

Cronbach's Alpha tells you how internally consistent your scale is:

Item-Total Correlation shows how well each item fits the scale:

Alpha if Item Deleted shows what happens if you remove an item:

McDonald's Omega

McDonald's Omega (omega total) is a factor-model-based reliability coefficient. Where alpha assumes every item measures the construct equally well (tau-equivalence), omega fits a one-factor model and lets each item carry its own loading. The two agree when items are roughly tau-equivalent; omega is typically slightly higher (and the more accurate estimate) when loadings differ across items, which is the common case in survey scales (Hayes & Coutts, 2020).

reliability() reports two variants, mirroring the two alpha variants: omega from the covariance metric (analogous to raw alpha) and omega_std from the correlation metric (analogous to standardized alpha). Omega if Item Deleted refits the one-factor model without each item, mirroring Alpha if Item Deleted.

A one-factor model needs at least 3 items to be identified: with fewer than 3 items the omega fields are NA (alpha is still computed), and Omega if Item Deleted is NA whenever the reduced scale would fall below 3 items.

Weighted variants and validation status

Cronbach's alpha and the item statistics are validated against SPSS v29 RELIABILITY output (weighted and unweighted). McDonald's omega is currently an R-only statistic (Tier 4 per the Validation Charter): SPSS offers omega from v27 onward, but IBM's algorithm documentation for it is not publicly retrievable and no SPSS v29 reference run exists yet. mariposa computes omega from a one-factor maximum-likelihood solution (the same estimator family as efa with fm = "ml"). The weighted omega uses the same weighted correlation and covariance matrices as the weighted alpha and reduces exactly to the unweighted omega when all weights equal 1 (enforced by an internal invariance suite); see vignette("spss-compatibility") for validation status.

When to Use This

Run reliability() before creating scale scores with row_means:

  1. Select your items

  2. Check reliability

  3. If acceptable (alpha > .70), create the index

  4. If not, review items and consider removing problematic ones

Value

A reliability result object containing:

alpha

Cronbach's Alpha (unstandardized)

alpha_standardized

Cronbach's Alpha based on standardized items

omega

McDonald's Omega (raw/total, one-factor ML model; NA for fewer than 3 items)

omega_std

Standardized Omega (correlation metric)

n_items

Number of items in the scale

item_statistics

Mean, SD, and N for each item

item_total

Corrected Item-Total Correlation, Alpha if Item Deleted, and Omega if Item Deleted

inter_item_cor

Inter-item correlation matrix

n

Sample size (listwise)

Use summary() for the full SPSS-style output with toggleable sections.

References

McDonald, R. P. (1999). Test Theory: A Unified Treatment. Mahwah, NJ: Lawrence Erlbaum.

Hayes, A. F., & Coutts, J. J. (2020). Use omega rather than Cronbach's alpha for estimating reliability. But... Communication Methods and Measures, 14(1), 1-24.

See Also

row_means for creating mean indices after checking reliability.

pearson_cor for bivariate correlations.

summary.reliability for detailed output with toggleable sections.

Other scale: efa(), pomps(), row_count(), row_means(), row_sums()

Examples

library(dplyr)
data(survey_data)

# Check reliability of trust items
reliability(survey_data, trust_government, trust_media, trust_science)

# With survey weights
reliability(survey_data, trust_government, trust_media, trust_science,
            weights = sampling_weight)

# Using tidyselect helpers
reliability(survey_data, starts_with("trust"))

# Grouped by region
survey_data %>%
  group_by(region) %>%
  reliability(trust_government, trust_media, trust_science)

# --- Three-layer output ---
result <- reliability(survey_data, trust_government, trust_media, trust_science)
result              # compact one-line overview
summary(result)     # full detailed output with all sections
summary(result, inter_item_correlations = FALSE)  # hide correlations


Count Occurrences of a Value Across Columns

Description

Counts how often a specific value appears in each row across the selected variables. Useful for data quality checks (e.g., "How many items did a respondent answer with -9?") or for creating count-based indices.

Usage

row_count(data, ..., count, na.rm = TRUE)

Arguments

data

Your survey data (a data frame or tibble).

...

The variables to check. Supports tidyselect.

count

The value to count.

na.rm

If TRUE (default), NA values are ignored. If FALSE, any row containing NA returns NA.

Value

An integer vector with one value per row — the count of how often count appears.

See Also

row_sums() for row-wise sums, row_means() for row-wise means

Other scale: efa(), pomps(), reliability(), row_means(), row_sums()

Examples

library(dplyr)
data(survey_data)

# How many items did each respondent answer with the highest value (5)?
survey_data <- survey_data %>%
  mutate(n_top = row_count(., trust_government, trust_media,
                           trust_science, count = 5))


Compute Row Means Across Items

Description

Calculates the mean across multiple variables for each row. This is the standard way to create scale scores from survey items — the R equivalent of SPSS's COMPUTE score = MEAN(var1, var2, var3).

Use min_valid to require a minimum number of non-missing items, mirroring SPSS's MEAN.n() syntax: min_valid = 2 corresponds to MEAN.2(a, b, c).

Usage

row_means(data, ..., min_valid = NULL, na.rm = TRUE)

Arguments

data

Your survey data (a data frame or tibble). When used inside mutate(), pass . or use pick().

...

The variables to average. Use bare column names separated by commas, or tidyselect helpers like starts_with("trust"). If no variables are specified, all numeric columns in data are used (useful with pick()).

min_valid

Minimum number of non-missing values required to compute a mean. If a row has fewer valid values, NA is returned. Default is NULL (compute mean if at least 1 value is valid).

na.rm

Remove missing values before calculating? Default: TRUE.

Details

How It Works

For each row, row_means() computes the arithmetic mean of the selected variables. Missing values are ignored by default, so a respondent who answered 2 out of 3 items still gets a score.

The min_valid Parameter

In practice, you often want to require a minimum number of valid responses. If someone only answered 1 out of 5 items, a mean based on a single item may not be reliable. Set min_valid to control this:

When to Use This

Use row_means() after checking reliability with reliability:

  1. Run reliability() to check if items form a reliable scale

  2. If Cronbach's Alpha is acceptable (typically > .70), create the index

  3. Use the index in further analyses (t-tests, correlations, regression)

Value

A numeric vector with one value per row — the mean across the selected variables. Use inside dplyr::mutate() to add it as a new column.

See Also

row_sums() for row-wise sums, row_count() for counting specific values, pomps() for rescaling to 0-100

Other scale: efa(), pomps(), reliability(), row_count(), row_sums()

Examples

library(dplyr)
data(survey_data)

# Create a trust scale from 3 items
survey_data <- survey_data %>%
  mutate(m_trust = row_means(., trust_government, trust_media, trust_science))

# Using pick()
survey_data <- survey_data %>%
  mutate(m_trust = row_means(pick(starts_with("trust"))))

# Require at least 2 valid items (like SPSS MEAN.2)
survey_data <- survey_data %>%
  mutate(m_trust = row_means(., trust_government, trust_media,
                             trust_science, min_valid = 2))


Compute Row Sums Across Items

Description

Calculates the sum across multiple variables for each row. This is the R equivalent of SPSS's COMPUTE total = SUM(var1, var2, var3).

Use min_valid to require a minimum number of non-missing items, mirroring SPSS's SUM.n() syntax.

Usage

row_sums(data, ..., min_valid = NULL, na.rm = TRUE)

Arguments

data

Your survey data (a data frame or tibble). When used inside mutate(), pass . or use pick().

...

The variables to average. Use bare column names separated by commas, or tidyselect helpers like starts_with("trust"). If no variables are specified, all numeric columns in data are used (useful with pick()).

min_valid

Minimum number of non-missing values required to compute a mean. If a row has fewer valid values, NA is returned. Default is NULL (compute mean if at least 1 value is valid).

na.rm

Remove missing values before calculating? Default: TRUE.

Details

When to Use row_sums() vs row_means()

Value

A numeric vector with one value per row — the sum across the selected variables.

See Also

row_means() for row-wise means, row_count() for counting specific values

Other scale: efa(), pomps(), reliability(), row_count(), row_means()

Examples

library(dplyr)
data(survey_data)

# Total score across items
survey_data <- survey_data %>%
  mutate(total = row_sums(., trust_government, trust_media, trust_science))

# With min_valid (like SPSS SUM.3)
survey_data <- survey_data %>%
  mutate(total = row_sums(., trust_government, trust_media,
                          trust_science, min_valid = 3))


Compare All Groups More Conservatively After ANOVA

Description

scheffe_test() tells you which groups differ after ANOVA, using the most conservative approach. It's like Tukey's test but even more careful about avoiding false positives.

Think of it as:

Usage

scheffe_test(x, conf.level = 0.95, ...)

## Default S3 method:
scheffe_test(x, conf.level = 0.95, ...)

Arguments

x

ANOVA results from oneway_anova()

conf.level

Confidence level for intervals (Default: 0.95 = 95%)

...

Additional arguments (currently unused)

Details

Understanding the Results

Adjusted P-values: Extra conservative to prevent false positives

Confidence Intervals: Wider than Tukey's

When to Use Scheffe Test

Use Scheffe test when:

Scheffe vs. Tukey

Scheffe Test:

Tukey Test:

Reading the Output

Example: "Group A - Group B: Diff = 3.2, p = 0.082"

Tips for Success

Value

Pairwise comparison results showing:

References

Scheffe, H. (1953). A method for judging all contrasts in the analysis of variance. Biometrika, 40(1-2), 87-110.

Scheffe, H. (1959). The Analysis of Variance. New York: Wiley.

See Also

oneway_anova for performing ANOVA tests.

tukey_test for Tukey HSD post-hoc tests.

levene_test for testing homogeneity of variances.

Other posthoc: dunn_test(), levene_test(), pairwise_wilcoxon(), tukey_test()

Examples

# Load required packages and data
library(dplyr)
data(survey_data)

# Perform ANOVA followed by Scheffe post-hoc test
anova_result <- survey_data %>%
  oneway_anova(life_satisfaction, group = education)

# Scheffe post-hoc comparisons
anova_result %>% scheffe_test()

# Multiple variables
anova_result_multi <- survey_data %>%
  oneway_anova(life_satisfaction, income, group = education)

anova_result_multi %>% scheffe_test()

# Weighted analysis
anova_weighted <- survey_data %>%
  oneway_anova(life_satisfaction, group = education, weights = sampling_weight)

anova_weighted %>% scheffe_test()

# Grouped analysis
anova_grouped <- survey_data %>%
  group_by(region) %>%
  oneway_anova(life_satisfaction, group = education)

anova_grouped %>% scheffe_test()

# Custom confidence level (99%)
anova_result %>% scheffe_test(conf.level = 0.99)


Declare Values as Missing

Description

Replaces specific numeric values with NA (or tagged NAs) across one or more variables. This is essential for data cleaning workflows where missing value codes (e.g., -9, -8, 99) are stored as regular values and need to be declared as missing after import.

Usage

set_na(data, ..., tag = TRUE, verbose = FALSE)

Arguments

data

A data frame, tibble, or a single vector.

...

Values to set as missing. Can be:

  • Unnamed numeric values: Applied to all numeric columns (e.g., set_na(data, -9, -8))

  • Named pairs: Applied to specific variables (e.g., set_na(data, income = c(-9, -8), age = -1))

tag

If TRUE (default), uses tagged NAs to preserve distinct missing types. The resulting tagged NAs integrate with na_frequencies(), frequency(), and codebook(). If FALSE, replaces with regular NA.

verbose

If TRUE, prints a summary of conversions.

Details

Tagged vs. Regular NA

When tag = TRUE (default), each missing value code gets a unique tag character, so you can distinguish between "No answer" (-9) and "Not applicable" (-8) in downstream analysis. This is the same system used by read_spss() with tag_na = TRUE.

When tag = FALSE, all specified values become regular NA and the distinction between different missing types is lost.

Interaction with Existing Labels

If a value being set to missing has an existing value label, that label is preserved as a tagged NA label (when tag = TRUE), making it visible in frequency() and codebook() output.

Value

The modified data (invisibly for data frames, visibly for vectors).

See Also

na_frequencies() for inspecting missing types, strip_tags() for converting tagged NAs to regular NA, untag_na() for recovering original codes

Other labels: copy_labels(), drop_labels(), find_var(), to_character(), to_label(), to_labelled(), to_numeric(), unlabel(), val_labels(), var_label()

Examples

# Use regular NA instead of tagged NA (no packages required)
data <- set_na(survey_data, -9, -8, tag = FALSE)

# Tagged NAs preserve the distinction between missing types
# (requires the haven package)
if (requireNamespace("haven", quietly = TRUE)) {
  # Set -9 and -8 as missing across all numeric variables
  data <- set_na(survey_data, -9, -8)

  # Set missing for specific variables only
  data <- set_na(survey_data,
    income = c(-9, -8, -42),
    life_satisfaction = c(-9, -11)
  )

  # Check the result
  na_frequencies(data$income)
}


Spearman's Rank Correlation Analysis

Description

Calculates Spearman's rank correlation coefficients (rho) between variables with support for weighted correlations, grouped data, and multiple variable pairs. Provides significance testing and SPSS-compatible output formatting.

Spearman's rho is a non-parametric measure of rank correlation that assesses monotonic relationships between variables. It is particularly suitable for ordinal data or when the assumptions of Pearson correlation are not met.

Usage

spearman_rho(
  data,
  ...,
  weights = NULL,
  alternative = c("two.sided", "less", "greater"),
  use = c("pairwise", "listwise"),
  na.rm = NULL
)

Arguments

data

Your survey data (a data frame or tibble)

...

The variables you want to correlate. List two for a single correlation or more for a correlation matrix. You can use helpers like starts_with("trust").

weights

Optional survey weights. Following the SPSS NONPAR CORR convention, weights are used only to filter cases (rows with weight <= 0 or NA are dropped); the rank correlation itself is computed unweighted on the remaining sample. For design-based weighted Spearman use survey::svyolr() or wCorr::weightedCorr(method = "Spearman").

alternative

Direction of the test:

  • "two.sided" (default): Two-tailed test

  • "less": One-tailed test (negative correlation)

  • "greater": One-tailed test (positive correlation)

use

How to handle missing values:

  • "pairwise" (default): Pairwise deletion - each correlation uses all available cases

  • "listwise": Listwise deletion - only complete cases across all variables

na.rm

Deprecated. Use use instead.

Details

Understanding the Results

Spearman's rho measures the strength and direction of a monotonic relationship between two variables. Unlike Pearson correlation, it does not require a linear relationship – it just needs one variable to consistently increase (or decrease) as the other increases. Think of it as ranking your data first, then checking if the ranks tend to go together.

The rho value ranges from -1 to +1:

The output also provides:

When to Use This

Choose Spearman's rho when:

Spearman vs. Kendall

Value

Correlation results showing rank-based relationships between variables, including the rho coefficient, p-value, t-statistic, and sample size for each pair. For multiple variables, correlation, significance, and sample size matrices are also provided. Use summary() for the full SPSS-style output with toggleable sections.

References

Spearman, C. (1904). The proof and measurement of association between two things. American Journal of Psychology, 15(1), 72–101.

Lehmann, E. L. (1975). Nonparametrics: Statistical Methods Based on Ranks. Holden-Day.

See Also

cor with method = "spearman" for the base R implementation.

kendall_tau for Kendall's rank correlation.

pearson_cor for Pearson correlation analysis.

summary.spearman_rho for detailed output with toggleable sections.

Other correlation: kendall_tau(), partial_cor(), pearson_cor()

Examples

# Load required packages and data
library(dplyr)
data(survey_data)

# Basic correlation between two variables
survey_data %>%
  spearman_rho(life_satisfaction, political_orientation)

# Correlation matrix for multiple variables
survey_data %>%
  spearman_rho(life_satisfaction, political_orientation, trust_media)

# Weighted correlations (mathematically correct, though SPSS may not apply weights)
survey_data %>%
  spearman_rho(age, income, weights = sampling_weight)

# Grouped correlations
survey_data %>%
  group_by(region) %>%
  spearman_rho(age, income, life_satisfaction)

# Using tidyselect helpers
survey_data %>%
  spearman_rho(starts_with("trust"), weights = sampling_weight)

# Listwise deletion for missing data
survey_data %>%
  spearman_rho(age, income, use = "listwise")

# One-tailed test
survey_data %>%
  spearman_rho(age, income, alternative = "greater")

# --- Three-layer output ---
result <- spearman_rho(survey_data, age, income, life_satisfaction)
result              # compact one-line overview
summary(result)     # full correlation, p-value, and N matrices
summary(result, pvalue_matrix = FALSE)  # hide p-values


Standardize Variables (Z-Scores)

Description

Standardizes variables by centering on the mean and dividing by a measure of spread. Supports multiple standardization methods including robust alternatives.

When used on a grouped data frame (via dplyr::group_by()), standardization is performed within each group.

Usage

std(data, ..., method = "sd", weights = NULL, suffix = NULL, na.rm = TRUE)

Arguments

data

A data frame or numeric vector.

...

Variables to standardize (tidyselect). Only used when data is a data frame.

method

Standardization method:

"sd"

Standard z-score: (x - mean) / sd (default)

"2sd"

Gelman's 2-SD method: (x - mean) / (2 * sd). Useful in regression with binary predictors.

"mad"

Robust: (x - median) / mad. Resistant to outliers.

"gmd"

Gini's Mean Difference: (x - mean) / gmd. A robust alternative.

weights

Optional survey weights (unquoted column name or numeric vector). When provided, weighted mean and weighted SD are used for standardization. Only supported for methods "sd" and "2sd".

suffix

A character string appended to column names (e.g., "_z"). If NULL (default), the original columns are overwritten.

na.rm

Remove missing values before computing mean and SD? Default: TRUE.

Details

Standardization Methods

Weighted Standardization

When weights is provided, the weighted mean and weighted standard deviation (using SPSS frequency weight formula) are used. This is only supported for methods "sd" and "2sd". The robust methods "mad" and "gmd" do not support weights.

Group-By Standardization

When data is grouped (via group_by()), standardization is performed separately within each group. This is useful for within-group comparisons. Weights are also subsetted per group.

Value

If data is a vector, a standardized numeric vector. If data is a data frame, the modified data frame (invisibly).

See Also

center() for mean-centering without scaling, pomps() for rescaling to 0-100

Other transform: center()

Examples

library(dplyr)
data(survey_data)

# Standard z-scores
data <- std(survey_data, age, income, suffix = "_z")

# Gelman 2-SD standardization (for regression)
data <- std(survey_data, income, age, method = "2sd",
            suffix = "_z")

# Robust standardization
data <- std(survey_data, income, method = "mad", suffix = "_z")

# Weighted standardization
data <- std(survey_data, income, age,
            weights = sampling_weight, suffix = "_z")

# Group-wise standardization
data <- survey_data %>%
  group_by(region) %>%
  std(income, suffix = "_z")


Strip Tags from Tagged NAs

Description

Converts all tagged NAs to regular (untagged) NA values, effectively removing the missing value type information. Works with data from any format: read_spss(), read_por(), read_stata(), read_sas(), or read_xpt().

Usage

strip_tags(x)

Arguments

x

A numeric vector with tagged NAs.

Value

A numeric vector where all tagged NAs have been replaced with regular NA. Value labels for missing types are removed; labels for valid values are preserved.

See Also

read_spss(), read_stata(), read_sas(), read_xpt(), na_frequencies(), untag_na()

Other data-import: na_frequencies(), read_por(), read_sas(), read_spss(), read_stata(), read_xlsx(), read_xpt(), untag_na()

Examples


if (requireNamespace("haven", quietly = TRUE)) {
  x <- set_na(c(1, 2, -9, 3, -8), -9, -8)
  # Remove tag information: all missings become plain NA
  strip_tags(x)
}



Summary method for ANCOVA results

Description

Creates a summary object that produces detailed output when printed, including the full ANOVA table, parameter estimates, estimated marginal means, and Levene's test.

Usage

## S3 method for class 'ancova'
summary(
  object,
  between_subjects = TRUE,
  parameter_estimates = TRUE,
  marginal_means = TRUE,
  levene_test = TRUE,
  digits = 3,
  ...
)

Arguments

object

An ancova result object.

between_subjects

Logical. Show the ANOVA table? (Default: TRUE)

parameter_estimates

Logical. Show parameter estimates? (Default: TRUE)

marginal_means

Logical. Show estimated marginal means? (Default: TRUE)

levene_test

Logical. Show Levene's test? (Default: TRUE)

digits

Number of decimal places for formatting (Default: 3).

...

Additional arguments (not used).

Value

A summary.ancova object.

See Also

ancova for the main analysis function.

Examples

result <- ancova(survey_data, dv = life_satisfaction, between = gender, covariate = age)
summary(result)
summary(result, marginal_means = FALSE)


Summary method for binomial test results

Description

Creates a summary object that produces detailed output when printed, including the category table with counts and observed proportions, and the test statistics table with test proportion, p-value, and confidence interval.

Usage

## S3 method for class 'binomial_test'
summary(object, categories = TRUE, results = TRUE, digits = 3, ...)

Arguments

object

A binomial_test result object.

categories

Logical. Show the category table? (Default: TRUE)

results

Logical. Show test statistics table? (Default: TRUE)

digits

Number of decimal places for formatting (Default: 3).

...

Additional arguments (not used).

Value

A summary.binomial_test object.

See Also

binomial_test for the main analysis function.

Examples

result <- binomial_test(survey_data, gender, p = 0.50)
summary(result)
summary(result, categories = FALSE)


Summary method for chi-squared test results

Description

Creates a summary object that produces detailed output when printed, including observed and expected frequency tables, test results, and effect size measures.

Usage

## S3 method for class 'chi_square'
summary(
  object,
  observed = TRUE,
  expected = TRUE,
  results = TRUE,
  effect_sizes = TRUE,
  digits = 3,
  ...
)

Arguments

object

A chi_square result object.

observed

Logical. Show observed frequency table? (Default: TRUE)

expected

Logical. Show expected frequency table? (Default: TRUE)

results

Logical. Show chi-squared test results table? (Default: TRUE)

effect_sizes

Logical. Show effect size measures? (Default: TRUE)

digits

Number of decimal places for formatting (Default: 3).

...

Additional arguments (not used).

Value

A summary.chi_square object.

See Also

chi_square for the main analysis function.

Examples

result <- chi_square(survey_data, gender, education)
summary(result)
summary(result, expected = FALSE)


Summary method for chi-square goodness-of-fit test results

Description

Creates a summary object that produces detailed output when printed, including the frequency table with observed, expected, and residual counts, and the test statistics table.

Usage

## S3 method for class 'chisq_gof'
summary(object, frequency_table = TRUE, results = TRUE, digits = 3, ...)

Arguments

object

A chisq_gof result object.

frequency_table

Logical. Show the frequency table with observed, expected, and residual counts? (Default: TRUE)

results

Logical. Show the test statistics table? (Default: TRUE)

digits

Number of decimal places for formatting (Default: 3).

...

Additional arguments (not used).

Value

A summary.chisq_gof object.

See Also

chisq_gof for the main analysis function.

Examples

result <- chisq_gof(survey_data, gender)
summary(result)
summary(result, frequency_table = FALSE)


Detailed Console Summary of the Codebook

Description

Creates a detailed summary object for console display, showing per-variable information with toggleable sections. Use this when you want detailed text output without opening the HTML Viewer.

Usage

## S3 method for class 'codebook'
summary(
  object,
  overview = TRUE,
  variable_details = TRUE,
  value_labels = TRUE,
  digits = 3,
  ...
)

Arguments

object

A codebook object from codebook()

overview

Show dataset-level overview? (Default: TRUE)

variable_details

Show per-variable detail blocks? (Default: TRUE)

value_labels

Show value labels within variable details? (Default: TRUE)

digits

Number of decimal places for numeric output (Default: 3)

...

Additional arguments (ignored)

Value

A summary.codebook object (printed by print.summary.codebook())

Examples

data(survey_data)
cb <- codebook(survey_data)
summary(cb)
summary(cb, value_labels = FALSE)


Summary method for crosstab results

Description

Creates a summary object that produces detailed output when printed, including the full cross-tabulation table with cell counts, marginal totals, and the requested percentage breakdowns.

Usage

## S3 method for class 'crosstab'
summary(
  object,
  crosstab_table = TRUE,
  percentages = TRUE,
  residuals = FALSE,
  digits = 1,
  ...
)

Arguments

object

A crosstab result object.

crosstab_table

Logical. Show the cross-tabulation table? (Default: TRUE)

percentages

Logical. Show the percentage sub-rows inside the table (as requested via the percentages argument of crosstab)? (Default: TRUE)

residuals

Logical. Show the adjusted standardized residual as a sub-row in each cell (SPSS CROSSTABS /CELLS=ASRESID)? After a significant chi_square test, cells with an absolute adjusted residual above roughly 2 are the ones deviating from independence. (Default: FALSE, matching SPSS's opt-in cell display)

digits

Number of decimal places for percentages (Default: 1).

...

Additional arguments (not used).

Value

A summary.crosstab object.

See Also

crosstab for the main analysis function.

Examples

result <- crosstab(survey_data, gender, region)
summary(result)
summary(result, percentages = FALSE)
summary(result, residuals = TRUE)   # which cells drive the association?


Summary method for describe results

Description

Creates a summary object that produces the descriptive statistics table when printed. Since describe() output is already a summary table by nature, the printed content matches print(); the summary layer adds the statistics section toggle and the digits formatting option for consistency with the other analysis functions.

Usage

## S3 method for class 'describe'
summary(object, statistics = TRUE, digits = 3, ...)

Arguments

object

A describe result object.

statistics

Logical. Show the descriptive statistics table? (Default: TRUE)

digits

Number of decimal places for formatting (Default: 3).

...

Additional arguments (not used).

Value

A summary.describe object.

See Also

describe for the main analysis function.

Examples

result <- describe(survey_data, age, income)
summary(result)
summary(result, digits = 2)


Summary method for Dunn post-hoc test results

Description

Creates a summary object that produces detailed output when printed, including the pairwise comparison tables with Z-statistics, unadjusted and adjusted p-values, and interpretation.

Usage

## S3 method for class 'dunn_test'
summary(object, comparisons = TRUE, interpretation = TRUE, digits = 3, ...)

Arguments

object

A dunn_test result object.

comparisons

Logical. Show the pairwise comparison tables? (Default: TRUE)

interpretation

Logical. Show the interpretation section? (Default: TRUE)

digits

Number of decimal places for formatting (Default: 3).

...

Additional arguments (not used).

Value

A summary.dunn_test object.

See Also

dunn_test for the main analysis function.

Examples

result <- kruskal_wallis(survey_data, life_satisfaction,
                         group = education) |> dunn_test()
summary(result)
summary(result, interpretation = FALSE)


Summarize an exploratory factor analysis

Description

Creates a detailed summary of an EFA result. All sections are shown by default; set individual toggles to FALSE to suppress specific sections.

Usage

## S3 method for class 'efa'
summary(
  object,
  kmo_bartlett = TRUE,
  communalities = TRUE,
  variance_explained = TRUE,
  unrotated_matrix = TRUE,
  rotated_matrix = TRUE,
  pattern_matrix = TRUE,
  structure_matrix = TRUE,
  factor_correlations = TRUE,
  digits = 3,
  ...
)

Arguments

object

An efa result object

kmo_bartlett

Show KMO and Bartlett's test? (Default: TRUE)

communalities

Show communalities table? (Default: TRUE)

variance_explained

Show total variance explained? (Default: TRUE)

unrotated_matrix

Show unrotated component/factor matrix? (Default: TRUE)

rotated_matrix

Show rotated matrix (varimax)? (Default: TRUE)

pattern_matrix

Show pattern matrix (oblimin/promax)? (Default: TRUE)

structure_matrix

Show structure matrix (oblimin/promax)? (Default: TRUE)

factor_correlations

Show factor correlation matrix (oblimin/promax)? (Default: TRUE)

digits

Number of decimal places (Default: 3)

...

Additional arguments (ignored)

Value

A summary.efa object (list with $show toggles)

See Also

efa for the main analysis function.

Examples

result <- efa(survey_data, political_orientation, environmental_concern,
             life_satisfaction, trust_government, trust_media, trust_science)
summary(result)
summary(result, communalities = FALSE)


Summary method for factorial ANOVA results

Description

Creates a summary object that produces detailed output when printed, including the full ANOVA table, descriptive statistics, and Levene's test.

Usage

## S3 method for class 'factorial_anova'
summary(
  object,
  between_subjects = TRUE,
  descriptives = TRUE,
  levene_test = TRUE,
  digits = 3,
  ...
)

Arguments

object

A factorial_anova result object.

between_subjects

Logical. Show the ANOVA table? (Default: TRUE)

descriptives

Logical. Show descriptive statistics? (Default: TRUE)

levene_test

Logical. Show Levene's test? (Default: TRUE)

digits

Number of decimal places for formatting (Default: 3).

...

Additional arguments (not used).

Value

A summary.factorial_anova object.

See Also

factorial_anova for the main analysis function.

Examples

result <- factorial_anova(survey_data, dv = life_satisfaction, between = c(gender, education))
summary(result)
summary(result, levene_test = FALSE)


Summary method for Fisher's exact test results

Description

Creates a summary object that produces detailed output when printed, including the contingency table of observed frequencies and the test results table with method, exact p-value, and sample size.

Usage

## S3 method for class 'fisher_test'
summary(object, contingency_table = TRUE, results = TRUE, digits = 3, ...)

Arguments

object

A fisher_test result object.

contingency_table

Logical. Show the contingency table? (Default: TRUE)

results

Logical. Show the test results table? (Default: TRUE)

digits

Number of decimal places for formatting (Default: 3).

...

Additional arguments (not used).

Value

A summary.fisher_test object.

See Also

fisher_test for the main analysis function.

Examples

result <- fisher_test(survey_data, row = gender, col = region)
summary(result)
summary(result, contingency_table = FALSE)


Summary method for frequency results

Description

Creates a summary object that produces detailed output when printed, including the per-variable summary statistics line (total N, valid N, mean, SD, skewness) and the full ASCII frequency tables with counts, raw/valid/cumulative percentages, and missing value breakdowns.

Usage

## S3 method for class 'frequency'
summary(object, frequency_table = TRUE, summary_stats = TRUE, digits = 2, ...)

Arguments

object

A frequency result object.

frequency_table

Logical. Show the frequency tables? (Default: TRUE)

summary_stats

Logical. Show the per-variable summary statistics line? (Default: TRUE)

digits

Number of decimal places for percentages and summary statistics (Default: 2).

...

Additional arguments (not used).

Value

A summary.frequency object.

See Also

frequency for the main analysis function.

Examples

result <- frequency(survey_data, gender)
summary(result)
summary(result, summary_stats = FALSE)


Summary method for Friedman test results

Description

Creates a summary object that produces detailed output when printed, including the mean rank table per measurement and the test statistics table with chi-square, p-value, and Kendall's W.

Usage

## S3 method for class 'friedman_test'
summary(object, ranks = TRUE, results = TRUE, digits = 3, ...)

Arguments

object

A friedman_test result object.

ranks

Logical. Show the mean rank table? (Default: TRUE)

results

Logical. Show test statistics table? (Default: TRUE)

digits

Number of decimal places for formatting (Default: 3).

...

Additional arguments (not used).

Value

A summary.friedman_test object.

See Also

friedman_test for the main analysis function.

Examples

result <- friedman_test(survey_data, trust_government, trust_media,
                        trust_science)
summary(result)
summary(result, ranks = FALSE)


Summary method for Kendall's tau correlation results

Description

Creates a summary object that produces detailed output when printed, including tau matrices, p-value matrices, and sample size matrices.

Usage

## S3 method for class 'kendall_tau'
summary(
  object,
  correlation_matrix = TRUE,
  pvalue_matrix = TRUE,
  n_matrix = TRUE,
  digits = 3,
  ...
)

Arguments

object

A kendall_tau result object.

correlation_matrix

Logical. Show the tau coefficient matrix? (Default: TRUE)

pvalue_matrix

Logical. Show the p-value matrix? (Default: TRUE)

n_matrix

Logical. Show the sample size matrix? (Default: TRUE)

digits

Number of decimal places for formatting (Default: 3).

...

Additional arguments (not used).

Value

A summary.kendall_tau object.

See Also

kendall_tau for the main analysis function.

Examples

result <- kendall_tau(survey_data[1:300, ], trust_government, trust_media)
summary(result)
summary(result, pvalue_matrix = FALSE)


Summary method for Kruskal-Wallis test results

Description

Creates a summary object that produces detailed output when printed, including rank statistics per group and the test statistics table with H, degrees of freedom, p-value, and epsilon-squared.

Usage

## S3 method for class 'kruskal_wallis'
summary(object, ranks = TRUE, results = TRUE, digits = 3, ...)

Arguments

object

A kruskal_wallis result object.

ranks

Logical. Show rank statistics per group? (Default: TRUE)

results

Logical. Show test statistics table? (Default: TRUE)

digits

Number of decimal places for formatting (Default: 3).

...

Additional arguments (not used).

Value

A summary.kruskal_wallis object.

See Also

kruskal_wallis for the main analysis function.

Examples

result <- kruskal_wallis(survey_data, life_satisfaction, group = education)
summary(result)
summary(result, ranks = FALSE)


Summary method for Levene test results

Description

Creates a summary object that produces detailed output when printed, including the per-variable results tables, the interpretation of the homogeneity-of-variance test, and the follow-up recommendation.

Usage

## S3 method for class 'levene_test'
summary(
  object,
  results = TRUE,
  interpretation = TRUE,
  recommendation = TRUE,
  digits = 3,
  ...
)

Arguments

object

A levene_test result object.

results

Logical. Show the test results tables? (Default: TRUE)

interpretation

Logical. Show the interpretation section? (Default: TRUE)

recommendation

Logical. Show the recommendation section (when available)? (Default: TRUE)

digits

Number of decimal places for formatting (Default: 3).

...

Additional arguments (not used).

Value

A summary.levene_test object.

See Also

levene_test for the main analysis function.

Examples

result <- levene_test(survey_data, life_satisfaction, group = education)
summary(result)
summary(result, interpretation = FALSE)


Summary method for linear regression results

Description

Creates a summary object that produces detailed output when printed, including model summary, ANOVA table, and coefficient table.

Usage

## S3 method for class 'linear_regression'
summary(
  object,
  model_summary = TRUE,
  anova_table = TRUE,
  coefficients = TRUE,
  conf_int = TRUE,
  collinearity = TRUE,
  descriptives = TRUE,
  digits = 3,
  ...
)

Arguments

object

A linear_regression result object.

model_summary

Logical. Show model summary (R, R-squared)? (Default: TRUE)

anova_table

Logical. Show ANOVA table? (Default: TRUE)

coefficients

Logical. Show coefficients table? (Default: TRUE)

conf_int

Logical. Show the confidence-interval columns for B in the coefficients table (SPSS /STATISTICS CI)? The interval level is the conf.level passed to linear_regression. (Default: TRUE)

collinearity

Logical. Show collinearity diagnostics (Tolerance, VIF per model term)? (Default: TRUE)

descriptives

Logical. Show the Descriptive Statistics table (Mean, SD, N for the dependent and predictor variables)? (Default: TRUE)

digits

Number of decimal places for formatting (Default: 3).

...

Additional arguments (not used).

Value

A summary.linear_regression object.

See Also

linear_regression for the main analysis function.

Examples

result <- linear_regression(survey_data, life_satisfaction ~ age + trust_government)
summary(result)
summary(result, descriptives = FALSE)
summary(result, conf_int = FALSE)   # hide the CI columns


Summary method for logistic regression results

Description

Creates a summary object that produces detailed output when printed, including omnibus test, model summary, Hosmer-Lemeshow test, classification table, and coefficient table.

Usage

## S3 method for class 'logistic_regression'
summary(
  object,
  omnibus_test = TRUE,
  model_summary = TRUE,
  hosmer_lemeshow = TRUE,
  classification = TRUE,
  coefficients = TRUE,
  digits = 3,
  ...
)

Arguments

object

A logistic_regression result object.

omnibus_test

Logical. Show omnibus test of model coefficients? (Default: TRUE)

model_summary

Logical. Show model summary (pseudo R-squared)? (Default: TRUE)

hosmer_lemeshow

Logical. Show Hosmer-Lemeshow test? (Default: TRUE)

classification

Logical. Show classification table? (Default: TRUE)

coefficients

Logical. Show coefficients table? (Default: TRUE)

digits

Number of decimal places for formatting (Default: 3).

...

Additional arguments (not used).

Value

A summary.logistic_regression object.

See Also

logistic_regression for the main analysis function.

Examples

survey_data$high_satisfaction <- ifelse(survey_data$life_satisfaction >= 4, 1, 0)
result <- logistic_regression(survey_data, high_satisfaction ~ age + income)
summary(result)
summary(result, classification = FALSE)


Summary method for Mann-Whitney test results

Description

Creates a summary object that produces detailed output when printed, including rank statistics per group, test results table with U, W, Z statistics, and effect size interpretation.

Usage

## S3 method for class 'mann_whitney'
summary(
  object,
  ranks = TRUE,
  results = TRUE,
  effect_sizes = TRUE,
  digits = 3,
  ...
)

Arguments

object

A mann_whitney result object.

ranks

Logical. Show rank statistics per group? (Default: TRUE)

results

Logical. Show test results table? (Default: TRUE)

effect_sizes

Logical. Show effect size output and interpretation? (Default: TRUE)

digits

Number of decimal places for formatting (Default: 3).

...

Additional arguments (not used).

Value

A summary.mann_whitney object.

See Also

mann_whitney for the main analysis function.

Examples

result <- mann_whitney(survey_data, life_satisfaction, group = gender)
summary(result)
summary(result, effect_sizes = FALSE)


Summary method for average marginal effects

Description

Creates a summary object that produces the detailed AME table (estimate, delta-method SE, z, p, confidence interval) when printed.

Usage

## S3 method for class 'marginal_effects'
summary(object, effects = TRUE, digits = 3, ...)

Arguments

object

A marginal_effects result object.

effects

Logical. Show the AME table? (Default: TRUE)

digits

Number of decimal places for formatting (Default: 3).

...

Additional arguments (not used).

Value

A summary.marginal_effects object.

See Also

marginal_effects for the main analysis function.

Examples

survey_data$high_satisfaction <- as.integer(survey_data$life_satisfaction >= 4)
model <- logistic_regression(survey_data, high_satisfaction ~ age + income)
summary(marginal_effects(model))


Summary method for McNemar test results

Description

Creates a summary object that produces detailed output when printed, including the 2x2 contingency table, the test results table with asymptotic and exact p-values, and the discordant pair counts.

Usage

## S3 method for class 'mcnemar_test'
summary(
  object,
  contingency_table = TRUE,
  results = TRUE,
  discordant_pairs = TRUE,
  digits = 3,
  ...
)

Arguments

object

A mcnemar_test result object.

contingency_table

Logical. Show the 2x2 contingency table? (Default: TRUE)

results

Logical. Show the test results table? (Default: TRUE)

discordant_pairs

Logical. Show the discordant pair counts? (Default: TRUE)

digits

Number of decimal places for formatting (Default: 3).

...

Additional arguments (not used).

Value

A summary.mcnemar_test object.

See Also

mcnemar_test for the main analysis function.

Examples

test_data <- transform(survey_data,
  trust_gov_high = as.integer(trust_government >= 4),
  trust_media_high = as.integer(trust_media >= 4))
result <- mcnemar_test(test_data, var1 = trust_gov_high,
                       var2 = trust_media_high)
summary(result)
summary(result, contingency_table = FALSE)


Summary method for multiple response results

Description

Creates a summary object that produces the detailed SPSS-style MULT RESPONSE output when printed: the frequencies table (percent of responses and of cases) and, when by was given, the crosstab with case-based column percentages.

Usage

## S3 method for class 'multiple_response'
summary(object, frequencies = TRUE, crosstab = TRUE, digits = 1, ...)

Arguments

object

A multiple_response result object.

frequencies

Logical. Show the frequencies table? (Default: TRUE)

crosstab

Logical. Show the by-crosstab (when by was given)? (Default: TRUE)

digits

Number of decimal places for percentages (Default: 1).

...

Additional arguments (not used).

Value

A summary.multiple_response object.

See Also

multiple_response for the main analysis function.

Examples

d <- survey_data
d$gov <- as.integer(d$trust_government >= 4)
d$media <- as.integer(d$trust_media >= 4)
summary(multiple_response(d, gov, media))


Summary method for normality test results

Description

Creates a summary object that produces the detailed SPSS-style "Tests of Normality" table when printed.

Usage

## S3 method for class 'normality_test'
summary(object, tests = TRUE, digits = 3, ...)

Arguments

object

A normality_test result object.

tests

Logical. Show the tests-of-normality table? (Default: TRUE)

digits

Number of decimal places for formatting (Default: 3).

...

Additional arguments (not used).

Value

A summary.normality_test object.

See Also

normality_test for the main analysis function.

Examples

result <- normality_test(survey_data, age, income)
summary(result)


Summary method for one-way ANOVA results

Description

Creates a summary object that produces detailed output when printed, including group descriptives, ANOVA table with Welch test, and effect sizes.

Usage

## S3 method for class 'oneway_anova'
summary(
  object,
  descriptives = TRUE,
  anova_table = TRUE,
  effect_sizes = TRUE,
  digits = 3,
  ...
)

Arguments

object

A oneway_anova result object.

descriptives

Logical. Show group descriptive statistics? (Default: TRUE)

anova_table

Logical. Show ANOVA results table and Welch test? (Default: TRUE)

effect_sizes

Logical. Show effect size measures? (Default: TRUE)

digits

Number of decimal places for formatting (Default: 3).

...

Additional arguments (not used).

Value

A summary.oneway_anova object.

See Also

oneway_anova for the main analysis function.

Examples

result <- oneway_anova(survey_data, life_satisfaction, group = education)
summary(result)
summary(result, effect_sizes = FALSE)


Summary method for pairwise Wilcoxon post-hoc test results

Description

Creates a summary object that produces detailed output when printed, including the pairwise comparison tables with Z-statistics, unadjusted and adjusted p-values, and interpretation.

Usage

## S3 method for class 'pairwise_wilcoxon'
summary(object, comparisons = TRUE, interpretation = TRUE, digits = 3, ...)

Arguments

object

A pairwise_wilcoxon result object.

comparisons

Logical. Show the pairwise comparison tables? (Default: TRUE)

interpretation

Logical. Show the interpretation section? (Default: TRUE)

digits

Number of decimal places for formatting (Default: 3).

...

Additional arguments (not used).

Value

A summary.pairwise_wilcoxon object.

See Also

pairwise_wilcoxon for the main analysis function.

Examples

result <- friedman_test(survey_data, trust_government, trust_media,
                        trust_science) |> pairwise_wilcoxon()
summary(result)
summary(result, interpretation = FALSE)


Summary method for partial correlation results

Description

Creates a summary object that produces detailed output when printed: the pairwise partial-correlation table (with zero-order comparison, df, t, and p) and — for three or more variables — the partial-correlation matrix.

Usage

## S3 method for class 'partial_cor'
summary(object, pairwise = TRUE, matrix = TRUE, digits = 3, ...)

Arguments

object

A partial_cor result object.

pairwise

Logical. Show the pairwise results table? (Default: TRUE)

matrix

Logical. Show the partial-correlation matrix (three or more analysis variables)? (Default: TRUE)

digits

Number of decimal places for formatting (Default: 3).

...

Additional arguments (not used).

Value

A summary.partial_cor object.

See Also

partial_cor for the main analysis function.

Examples

result <- partial_cor(survey_data, trust_government, trust_media,
                      trust_science, controls = age)
summary(result)
summary(result, matrix = FALSE)


Summary method for Pearson correlation results

Description

Creates a summary object that produces detailed output when printed, including correlation matrices, p-value matrices, and sample size matrices.

Usage

## S3 method for class 'pearson_cor'
summary(
  object,
  correlation_matrix = TRUE,
  pvalue_matrix = TRUE,
  n_matrix = TRUE,
  digits = 3,
  ...
)

Arguments

object

A pearson_cor result object.

correlation_matrix

Logical. Show the correlation coefficient matrix? (Default: TRUE)

pvalue_matrix

Logical. Show the p-value matrix? (Default: TRUE)

n_matrix

Logical. Show the sample size matrix? (Default: TRUE)

digits

Number of decimal places for formatting (Default: 3).

...

Additional arguments (not used).

Value

A summary.pearson_cor object.

See Also

pearson_cor for the main analysis function.

Examples

result <- pearson_cor(survey_data, trust_government, trust_media)
summary(result)
summary(result, pvalue_matrix = FALSE)


Summarize a reliability analysis

Description

Creates a detailed summary of a reliability analysis result. All sections are shown by default; set individual toggles to FALSE to suppress specific sections.

Usage

## S3 method for class 'reliability'
summary(
  object,
  reliability_statistics = TRUE,
  item_statistics = TRUE,
  inter_item_correlations = TRUE,
  item_total_statistics = TRUE,
  digits = 3,
  ...
)

Arguments

object

A reliability result object

reliability_statistics

Show Cronbach's Alpha and McDonald's Omega statistics? (Default: TRUE)

item_statistics

Show per-item means and SDs? (Default: TRUE)

inter_item_correlations

Show inter-item correlation matrix? (Default: TRUE)

item_total_statistics

Show item-total statistics? (Default: TRUE)

digits

Number of decimal places (Default: 3)

...

Additional arguments (ignored)

Value

A summary.reliability object (list with $show toggles)

See Also

reliability for the main analysis function.

Examples

result <- reliability(survey_data, trust_government, trust_media, trust_science)
summary(result)
summary(result, inter_item_correlations = FALSE)


Summary method for Scheffe test results

Description

Creates a summary object that produces detailed output when printed, including the pairwise comparison tables with mean differences, confidence intervals, Scheffe-adjusted p-values, and interpretation.

Usage

## S3 method for class 'scheffe_test'
summary(
  object,
  parameters = TRUE,
  comparisons = TRUE,
  interpretation = TRUE,
  digits = 3,
  ...
)

Arguments

object

A scheffe_test result object.

parameters

Logical. Show test parameters (confidence level, method notes)? (Default: TRUE)

comparisons

Logical. Show the pairwise comparison tables? (Default: TRUE)

interpretation

Logical. Show the interpretation section? (Default: TRUE)

digits

Number of decimal places for formatting (Default: 3).

...

Additional arguments (not used).

Value

A summary.scheffe_test object.

See Also

scheffe_test for the main analysis function.

Examples

result <- oneway_anova(survey_data, life_satisfaction,
                       group = education) |> scheffe_test()
summary(result)
summary(result, interpretation = FALSE)


Summary method for Spearman correlation results

Description

Creates a summary object that produces detailed output when printed, including rho matrices, p-value matrices, and sample size matrices.

Usage

## S3 method for class 'spearman_rho'
summary(
  object,
  correlation_matrix = TRUE,
  pvalue_matrix = TRUE,
  n_matrix = TRUE,
  digits = 3,
  ...
)

Arguments

object

A spearman_rho result object.

correlation_matrix

Logical. Show the rho coefficient matrix? (Default: TRUE)

pvalue_matrix

Logical. Show the p-value matrix? (Default: TRUE)

n_matrix

Logical. Show the sample size matrix? (Default: TRUE)

digits

Number of decimal places for formatting (Default: 3).

...

Additional arguments (not used).

Value

A summary.spearman_rho object.

See Also

spearman_rho for the main analysis function.

Examples

result <- spearman_rho(survey_data, trust_government, trust_media)
summary(result)
summary(result, pvalue_matrix = FALSE)


Summary method for t-test results

Description

Creates a summary object that produces detailed output when printed, including group descriptives, test results with both variance assumptions, effect sizes, and confidence intervals.

Usage

## S3 method for class 't_test'
summary(
  object,
  descriptives = TRUE,
  results = TRUE,
  effect_sizes = TRUE,
  digits = 3,
  ...
)

Arguments

object

A t_test result object.

descriptives

Logical. Show group descriptive statistics? (Default: TRUE)

results

Logical. Show test results table? (Default: TRUE)

effect_sizes

Logical. Show effect size measures? (Default: TRUE)

digits

Number of decimal places for formatting (Default: 3).

...

Additional arguments (not used).

Value

A summary.t_test object.

See Also

t_test for the main analysis function.

Examples

result <- t_test(survey_data, life_satisfaction, group = gender)
summary(result)
summary(result, effect_sizes = FALSE)


Summary method for Tukey HSD test results

Description

Creates a summary object that produces detailed output when printed, including the pairwise comparison tables with mean differences, confidence intervals, Tukey-adjusted p-values, and interpretation.

Usage

## S3 method for class 'tukey_test'
summary(
  object,
  parameters = TRUE,
  comparisons = TRUE,
  interpretation = TRUE,
  digits = 3,
  ...
)

Arguments

object

A tukey_test result object.

parameters

Logical. Show test parameters (confidence level, method notes)? (Default: TRUE)

comparisons

Logical. Show the pairwise comparison tables? (Default: TRUE)

interpretation

Logical. Show the interpretation section? (Default: TRUE)

digits

Number of decimal places for formatting (Default: 3).

...

Additional arguments (not used).

Value

A summary.tukey_test object.

See Also

tukey_test for the main analysis function.

Examples

result <- oneway_anova(survey_data, life_satisfaction,
                       group = education) |> tukey_test()
summary(result)
summary(result, interpretation = FALSE)


Summary method for Wilcoxon signed-rank test results

Description

Creates a summary object that produces detailed output when printed, including the rank table (negative/positive ranks, ties) and the test statistics table with Z, p-value, and effect size r.

Usage

## S3 method for class 'wilcoxon_test'
summary(object, ranks = TRUE, results = TRUE, digits = 3, ...)

Arguments

object

A wilcoxon_test result object.

ranks

Logical. Show the rank table? (Default: TRUE)

results

Logical. Show test statistics table? (Default: TRUE)

digits

Number of decimal places for formatting (Default: 3).

...

Additional arguments (not used).

Value

A summary.wilcoxon_test object.

See Also

wilcoxon_test for the main analysis function.

Examples

result <- wilcoxon_test(survey_data, x = trust_government, y = trust_media)
summary(result)
summary(result, ranks = FALSE)


Social Survey Data (Synthetic)

Description

A synthetic dataset modeled after large-scale social surveys with demographics, attitudes, and survey design features. Created for testing and demonstration purposes without licensing concerns.

Usage

survey_data

Format

A data frame with 2,500 rows and 16 variables:

id

Unique identifier (1-2500)

age

Age in years (18-95)

gender

Gender (Male, Female)

region

Region (East, West)

education

Education level (Basic Secondary, Intermediate Secondary, Academic Secondary, University)

income

Monthly household income in EUR (800-15000)

employment

Employment status (Student, Employed, Unemployed, Retired, Other)

political_orientation

Political orientation (1=very left to 5=very right)

environmental_concern

Environmental concern (1=not concerned to 5=very concerned)

life_satisfaction

Life satisfaction (1=very dissatisfied to 5=very satisfied)

trust_government

Trust in government (1=no trust to 5=complete trust)

trust_media

Trust in media (1=no trust to 5=complete trust)

trust_science

Trust in science (1=no trust to 5=complete trust)

sampling_weight

Post-stratification sampling weight (0.7-1.4)

stratum

Stratification variable combining region and age group

interview_mode

Interview mode (Face-to-face, Telephone, Online)

Details

This dataset contains realistic patterns of correlation between variables:

The data includes proper variable labels and follows social survey conventions for coding and structure. Generated with set.seed(2024) for reproducibility.

Source

Generated synthetically using realistic demographic and attitudinal patterns. No real survey data was used.

See Also

describe for descriptive statistics of numeric variables.

frequency for categorical frequency tables.

t_test for group comparisons.

Examples

# Load required packages and data
library(dplyr)
data(survey_data)

# Basic descriptive statistics
survey_data %>% describe(age, income, weights = sampling_weight)

# Frequency analysis
survey_data %>% frequency(education, region, weights = sampling_weight)

# Group comparisons
survey_data %>%
  group_by(region) %>%
  t_test(life_satisfaction, group = gender, weights = sampling_weight)


Test If Two Groups Differ

Description

t_test() helps you determine if two groups have different average values. For example, do men and women have different satisfaction scores? Does Region A spend more than Region B? Is this year better than last year?

The test tells you:

Usage

t_test(
  data,
  ...,
  group = NULL,
  weights = NULL,
  var.equal = FALSE,
  mu = 0,
  alternative = c("two.sided", "less", "greater"),
  conf.level = 0.95
)

Arguments

data

Your survey data (a data frame or tibble)

...

The numeric variables to test. List multiple variables or use tidyselect helpers like starts_with("trust").

group

The variable that defines your two groups (e.g., gender, region). Must have exactly two categories. Leave empty for one-sample tests.

weights

Optional survey weights for population-representative results

var.equal

Should we assume equal variances? (Default: FALSE)

  • FALSE: Safer, works even if groups vary differently (Welch's test)

  • TRUE: Traditional approach, assumes equal spread (Student's test)

mu

Comparison value (Default: 0). For two-sample tests, usually 0. For one-sample tests, your benchmark value.

alternative

Direction of the test:

  • "two.sided" (default): Any difference

  • "greater": First group is higher

  • "less": First group is lower

conf.level

Confidence level for intervals (Default: 0.95 = 95%)

Details

Understanding the Results

P-value: Is the difference statistically significant?

Effect Sizes (How big is the difference?):

Confidence Interval: Range where the true difference likely falls

When to Use This

Use t-test when:

Don't use when:

Reading the Output

The results show both variance assumptions:

A result with t = 2.45, p = 0.015, d = 0.62 means:

Tips for Success

Value

Test results showing whether groups differ, including:

References

Cohen, J. (1988). Statistical Power Analysis for the Behavioral Sciences (2nd ed.). Lawrence Erlbaum Associates.

Hedges, L. V. (1981). Distribution theory for Glass's estimator of effect size and related estimators. Journal of Educational Statistics, 6(2), 107-128.

Glass, G. V. (1976). Primary, secondary, and meta-analysis of research. Educational Researcher, 5(10), 3-8.

Welch, B. L. (1947). The generalization of "Student's" problem when several different population variances are involved. Biometrika, 34(1-2), 28-35.

See Also

t.test for the base R t-test function.

print.t_test for printing results.

group_by for grouped analyses.

summary.t_test for detailed output with toggleable sections.

Other hypothesis_tests: ancova(), binomial_test(), chi_square(), chisq_gof(), factorial_anova(), fisher_test(), friedman_test(), kruskal_wallis(), mann_whitney(), mcnemar_test(), oneway_anova(), wilcoxon_test()

Examples

# Load required packages and data
library(dplyr)
data(survey_data)

# Basic two-sample test
survey_data %>%
  t_test(life_satisfaction, group = gender)

# With survey weights
survey_data %>%
  t_test(life_satisfaction, group = gender, weights = sampling_weight)

# Multiple variables
survey_data %>%
  t_test(age, income, life_satisfaction, group = region, weights = sampling_weight)

# One-sample test against a benchmark
survey_data %>%
  t_test(life_satisfaction, mu = 5, weights = sampling_weight)

# Grouped analysis
survey_data %>%
  group_by(region) %>%
  t_test(life_satisfaction, group = gender, weights = sampling_weight)

# Equal variance assumption
survey_data %>%
  t_test(life_satisfaction, group = gender, var.equal = TRUE)

# One-sided test
survey_data %>%
  t_test(income, group = gender, alternative = "greater")

# Using tidyselect helpers
survey_data %>%
  t_test(starts_with("trust"), group = gender, weights = sampling_weight)

# Store results for further analysis
result <- survey_data %>%
  t_test(life_satisfaction, group = gender, weights = sampling_weight)
print(result)

# --- Three-layer output ---
result <- t_test(survey_data, life_satisfaction, group = gender)
result              # compact one-line summary
summary(result)     # full detailed output with all sections
summary(result, effect_sizes = FALSE)  # hide effect sizes


Convert Labelled Variables to Character

Description

Converts haven_labelled variables to character vectors using value labels as text. Same as to_label() but returns character instead of factor.

Usage

to_character(
  data,
  ...,
  drop_na = TRUE,
  add_non_labelled = FALSE,
  drop.na = NULL,
  add.non.labelled = NULL
)

Arguments

data

A data frame, tibble, or a single vector.

...

Optional: unquoted variable names (tidyselect supported). If empty, converts all haven_labelled columns.

drop_na

If TRUE (default), tagged NAs become regular NA.

add_non_labelled

If TRUE, unlabelled values are included as their numeric string representation. Default: FALSE.

drop.na, add.non.labelled

Defunct dot-case argument names, removed in mariposa 0.6.9. Calling the function with any of them is an error; use the snake_case equivalents instead. (The formals are retained only so that the old names error clearly instead of being swallowed by ....)

Details

This is a convenience wrapper around to_label() that calls as.character() on the result. Use this when you need character output (e.g., for string operations) rather than factor output.

The variable label ("label" attribute) is preserved on the output.

Value

The input with labelled variables converted to character. For single vector input, returns a character vector.

See Also

to_label() for factor output, val_labels()

Other labels: copy_labels(), drop_labels(), find_var(), set_na(), to_label(), to_labelled(), to_numeric(), unlabel(), val_labels(), var_label()

Examples

# Convert a single variable to character
to_character(survey_data$gender)

# Convert specific columns in a data frame
data <- to_character(survey_data, gender, region)


Create Dummy Variables (One-Hot Encoding)

Description

Creates 0/1 dummy variables from categorical variables. Column names are derived from value labels when available, making results readable for SPSS-style data.

Unlike model.matrix(), to_dummy() uses value labels for column naming and handles haven_labelled vectors correctly.

Usage

to_dummy(data, ..., suffix = "val", ref = NULL, append = TRUE)

Arguments

data

A data frame or vector. When a data frame is passed, use ... to select variables.

...

Variables to dummy-code (tidyselect). Only used when data is a data frame.

suffix

How to name dummy columns: "val" (default) uses the raw value (e.g., gender_1), "label" uses the value label (e.g., gender_Male).

ref

A value to use as reference category (omitted from output). If NULL (default), all categories get a dummy variable. Set to a specific value for n-1 coding (e.g., for regression).

append

If TRUE (default), the dummy columns are appended to the original data frame. If FALSE, only the dummy columns are returned. Ignored when data is a vector.

Details

Column Naming

With suffix = "val": {varname}_{value} (e.g., gender_1, gender_2). With suffix = "label": {varname}_{label} where labels are cleaned (spaces replaced with _, special characters removed).

Reference Category

For regression, you typically need n-1 dummy variables. Set ref to the value of the reference category to omit it.

Value

If append = TRUE (default), the original data frame with dummy columns appended. If append = FALSE, a tibble with only the dummy columns. For vector input, always a tibble of dummy columns.

See Also

rec() for general recoding, to_label() for converting to factor

Other recode: rec()

Examples

library(dplyr)
data(survey_data)

# Create dummies and append to data (default)
data <- to_dummy(survey_data, gender)

# Use labels for column names
data <- to_dummy(survey_data, gender, suffix = "label")

# n-1 dummies with reference category
data <- to_dummy(survey_data, gender, ref = 1)

# Multiple variables
data <- to_dummy(survey_data, gender, education, suffix = "label")

# Return only the dummy columns (without original data)
dummies <- to_dummy(survey_data, gender, append = FALSE)


Convert Labelled Variables to Factors

Description

Converts haven_labelled variables to factors, using value labels as factor levels. This is the primary function for making labelled survey data ready for plotting, cross-tabulation, and regression analysis.

Usage

to_label(
  data,
  ...,
  ordered = FALSE,
  drop_na = TRUE,
  drop_unused = FALSE,
  add_non_labelled = FALSE,
  drop.na = NULL,
  drop.unused = NULL,
  add.non.labelled = NULL
)

Arguments

data

A data frame, tibble, or a single vector.

...

Optional: unquoted variable names (tidyselect supported). If empty, converts all haven_labelled columns.

ordered

If TRUE, creates an ordered factor. Default: FALSE.

drop_na

If TRUE (default), tagged NAs are converted to regular NA (excluded from factor levels). If FALSE, tagged NAs are kept as factor levels with their label text.

drop_unused

If TRUE, removes factor levels with zero observations. Default: FALSE.

add_non_labelled

If TRUE, values without labels are included as factor levels using their numeric value as the level name. Default: FALSE (unlabelled values become NA).

drop.na, drop.unused, add.non.labelled

Defunct dot-case argument names, removed in mariposa 0.6.9. Calling the function with any of them is an error; use the snake_case equivalents instead. (The formals are retained only so that the old names error clearly instead of being swallowed by ....)

Details

For each labelled variable, the numeric codes are replaced by their associated value labels. The resulting factor levels are ordered by the original numeric values (not alphabetically).

When to Use This

Use to_label() when you:

Value

The input with labelled variables converted to factors. For single vector input, returns a factor.

See Also

to_character() for character output, to_labelled() for the reverse operation, val_labels() for viewing labels

Other labels: copy_labels(), drop_labels(), find_var(), set_na(), to_character(), to_labelled(), to_numeric(), unlabel(), val_labels(), var_label()

Examples

# Convert a single variable
to_label(survey_data$gender)

# Convert specific columns in a data frame
data <- to_label(survey_data, gender, region)

# Convert all labelled columns
data <- to_label(survey_data)

# Keep values without labels as factor levels
to_label(survey_data$life_satisfaction, add_non_labelled = TRUE)


Convert Variables to Labelled Format

Description

Converts factors, character vectors, or plain numeric vectors to haven_labelled class, optionally assigning value labels and a variable label. This is the reverse of to_label().

Usage

to_labelled(data, ..., labels = NULL, label = NULL)

Arguments

data

A data frame, tibble, or a single vector.

...

Optional: unquoted variable names (tidyselect supported). If empty on a data frame, converts all factor columns.

labels

Optional: a named numeric vector of value labels to assign. If NULL and the input is a factor, factor levels are used as labels.

label

Optional: a variable label string.

Details

Factor Conversion

When converting a factor, the integer codes (1, 2, 3, ...) become the numeric values and the factor levels become the value labels.

Character Conversion

Character vectors are converted to numeric (sequential integers) with the unique character values as labels.

Value

The input with variables converted to haven_labelled. For single vector input, returns a haven_labelled vector.

See Also

to_label() for the reverse operation, val_labels() for setting labels on existing labelled vectors

Other labels: copy_labels(), drop_labels(), find_var(), set_na(), to_character(), to_label(), to_numeric(), unlabel(), val_labels(), var_label()

Examples

# Factor -> haven_labelled
x <- factor(c("Male", "Female", "Male"))
to_labelled(x)

# Numeric with custom labels
to_labelled(c(1, 2, 3),
  labels = c("Low" = 1, "Medium" = 2, "High" = 3),
  label = "Satisfaction level"
)

# All factors in a data frame
data <- to_labelled(survey_data)


Convert Factors or Labelled Variables to Numeric

Description

Converts factor levels or labelled values to numeric. For factors, uses the underlying integer codes (or the numeric value of levels if they are numeric strings). For labelled variables, extracts the underlying numeric values.

Usage

to_numeric(
  data,
  ...,
  use_labels = TRUE,
  start_at = NULL,
  keep_labels = FALSE,
  use.labels = NULL,
  start.at = NULL,
  keep.labels = NULL
)

Arguments

data

A data frame, tibble, or a single vector.

...

Optional: unquoted variable names (tidyselect supported). If empty, converts all factor columns.

use_labels

If TRUE (default), attempts to use the numeric value of factor levels (e.g., level "3" becomes 3). If FALSE, uses sequential integers (1, 2, 3, ...).

start_at

If not NULL, the lowest numeric value in the output starts at this number. Default: NULL (use original values).

keep_labels

If TRUE, the former factor levels are stored as value labels on the result. Default: FALSE.

use.labels, start.at, keep.labels

Defunct dot-case argument names, removed in mariposa 0.6.9. Calling the function with any of them is an error; use the snake_case equivalents instead. (The formals are retained only so that the old names error clearly instead of being swallowed by ....)

Details

This function handles three input types:

  1. Numeric factors (levels like "1", "2", "3"): Extracts the numeric values from the level names.

  2. Text factors (levels like "Male", "Female"): Converts to sequential integers by default; use use_labels = FALSE to force this behavior even for numeric-looking levels.

  3. haven_labelled: Extracts the underlying numeric vector, stripping the labelled class.

Value

The input with variables converted to numeric. For single vector input, returns a numeric vector.

See Also

to_label() for the reverse (numeric -> factor), to_labelled() for creating labelled vectors

Other labels: copy_labels(), drop_labels(), find_var(), set_na(), to_character(), to_label(), to_labelled(), unlabel(), val_labels(), var_label()

Examples

# Numeric factor levels -> numeric
x <- factor(c("1", "3", "5", "3"))
to_numeric(x)
# [1] 1 3 5 3

# Sequential integers
to_numeric(x, use_labels = FALSE)
# [1] 1 2 3 2

# Haven labelled -> plain numeric
to_numeric(survey_data$life_satisfaction)


Find Which Specific Groups Differ After ANOVA

Description

tukey_test() tells you exactly which groups are different from each other after ANOVA finds overall differences. It's like a follow-up investigation that pinpoints where the differences lie.

Think of it as:

Usage

tukey_test(x, conf.level = 0.95, ...)

## Default S3 method:
tukey_test(x, conf.level = 0.95, ...)

Arguments

x

ANOVA results from oneway_anova()

conf.level

Confidence level for intervals (Default: 0.95 = 95%)

...

Additional arguments (currently unused)

Details

Understanding the Results

Adjusted P-values: Control for multiple comparisons

Mean Differences:

When to Use Tukey Test

Use Tukey test when:

Tukey vs. Scheffe

Tukey Test:

Scheffe Test:

Reading the Output

Example: "Group A - Group B: Diff = 3.2, p = 0.012"

Tips for Success

Value

Pairwise comparison results showing:

References

Tukey, J. W. (1949). Comparing individual means in the analysis of variance. Biometrics, 5(2), 99-114.

Kramer, C. Y. (1956). Extension of multiple range tests to group means with unequal numbers of replications. Biometrics, 12(3), 307-310.

See Also

oneway_anova for performing ANOVA tests.

TukeyHSD for the base R Tukey HSD function.

levene_test for testing homogeneity of variances.

Other posthoc: dunn_test(), levene_test(), pairwise_wilcoxon(), scheffe_test()

Examples

# Load required packages and data
library(dplyr)
data(survey_data)

# Perform ANOVA followed by Tukey post-hoc test
anova_result <- survey_data %>%
  oneway_anova(life_satisfaction, group = education)

# Tukey post-hoc comparisons
anova_result %>% tukey_test()

# With weights
anova_weighted <- survey_data %>%
  oneway_anova(life_satisfaction, group = education, weights = sampling_weight)

anova_weighted %>% tukey_test()

# Multiple variables
anova_multi <- survey_data %>%
  oneway_anova(trust_government, trust_science, group = education)

anova_multi %>% tukey_test()

# Grouped analysis
anova_grouped <- survey_data %>%
  group_by(region) %>%
  oneway_anova(life_satisfaction, group = education)

anova_grouped %>% tukey_test()


Remove All Label Metadata

Description

Strips all label-related attributes from variables, converting haven_labelled vectors to their base R types (numeric or character). This is useful when you need plain data without any labelling for functions or packages that do not support labelled data.

Usage

unlabel(data, ...)

Arguments

data

A data frame, tibble, or a single vector.

...

Optional: unquoted variable names (tidyselect supported). If empty, applies to all columns.

Details

The following attributes are removed:

Tagged NAs are converted to regular NA.

Value

The data with all labelling removed. haven_labelled numeric vectors become plain double, factors remain factors (but lose their "label" attribute).

See Also

strip_tags() for removing only tagged NAs, to_label() for converting to factors (preserving label info)

Other labels: copy_labels(), drop_labels(), find_var(), set_na(), to_character(), to_label(), to_labelled(), to_numeric(), val_labels(), var_label()

Examples

# Remove all labels from the entire dataset
data_plain <- unlabel(survey_data)

# Remove labels from specific variables only
data <- unlabel(survey_data, gender, life_satisfaction)


Convert Tagged NAs Back to Original Codes

Description

Replaces tagged NAs with their original missing value codes. Works with data imported via read_spss() (with tag_na = TRUE) or any reader that used the tag_na parameter (read_stata(), read_sas(), read_xpt()). For native Stata/SAS tagged NAs (e.g., .a, .A) that have no numeric codes to recover, use strip_tags() instead.

Usage

untag_na(x)

Arguments

x

A numeric vector with tagged NAs.

Value

A numeric vector where tagged NAs with numeric codes have been replaced with their original values (e.g., -9, -8, -42). System NAs (untagged) remain as NA. For native Stata/SAS tagged NAs (no numeric codes), falls back to strip_tags() behavior with a warning.

See Also

read_spss(), read_stata(), read_sas(), na_frequencies(), strip_tags()

Other data-import: na_frequencies(), read_por(), read_sas(), read_spss(), read_stata(), read_xlsx(), read_xpt(), strip_tags()

Examples


if (requireNamespace("haven", quietly = TRUE)) {
  # Tag -9/-8 as missing, then recover the original codes
  x <- set_na(c(1, 2, -9, 3, -8), -9, -8)
  untag_na(x)   # -9 and -8 are back
}



Get or Set Value Labels

Description

Retrieves or assigns value labels (the "labels" attribute) on labelled vectors or data frame columns. Value labels map numeric codes to descriptive text (e.g., 1 = "Male", 2 = "Female").

The function operates in two modes:

Usage

val_labels(data, ..., .add = FALSE, drop_na = TRUE)

Arguments

data

A data frame, tibble, or a single vector.

...

In GET mode: unquoted variable names (tidyselect supported). In SET mode: named pairs where the name is a variable and the value is a named vector of labels (e.g., c("Male" = 1, "Female" = 2)). Use NULL to remove all value labels from a variable.

.add

If TRUE, adds labels to any existing ones instead of replacing them. Default: FALSE.

drop_na

If TRUE (default), tagged NA labels are excluded from GET results.

Details

Value labels are stored as the "labels" attribute in haven's format: a named numeric vector where names are the label text and values are the numeric codes. This is the standard used by read_spss(), read_stata(), and read_sas().

Adding vs. Replacing Labels

By default, SET mode replaces all existing value labels. Use .add = TRUE to keep existing labels and only add new ones. If a value already has a label, the new label overwrites it.

Value

See Also

var_label() for variable labels, to_label() for converting labelled vectors to factors, drop_labels() for removing unused labels

Other labels: copy_labels(), drop_labels(), find_var(), set_na(), to_character(), to_label(), to_labelled(), to_numeric(), unlabel(), var_label()

Examples

# GET: retrieve value labels from a vector
val_labels(survey_data$gender)

# GET: from specific variables (returns list)
val_labels(survey_data, gender, region)

# SET: assign value labels
data <- val_labels(survey_data,
  gender = c("Male" = 1, "Female" = 2, "Non-binary" = 3)
)

# ADD: add labels without removing existing ones
data <- val_labels(data,
  gender = c("Prefer not to say" = 4),
  .add = TRUE
)

# REMOVE: set to NULL
data <- val_labels(data, gender = NULL)


Get or Set Variable Labels

Description

Retrieves or assigns variable labels (the "label" attribute) on vectors or data frame columns. Variable labels describe what a variable measures (e.g., "Age of respondent") and are commonly used in survey data imported from SPSS, Stata, or SAS.

The function operates in two modes:

Usage

var_label(data, ...)

Arguments

data

A data frame, tibble, or a single vector.

...

In GET mode: unquoted variable names (tidyselect supported). If empty, returns labels for all variables. In SET mode: named pairs where the name is a variable and the value is the label string. Use NULL to remove a label.

Details

Variable labels are stored as the "label" attribute on each column, which is the standard used by the haven package for SPSS/Stata/SAS imports. These labels are preserved by mariposa's codebook(), frequency(), and describe() functions.

When to Use This

Use var_label() when you:

Value

See Also

val_labels() for value labels, codebook() for viewing all metadata, copy_labels() for preserving labels after dplyr operations

Other labels: copy_labels(), drop_labels(), find_var(), set_na(), to_character(), to_label(), to_labelled(), to_numeric(), unlabel(), val_labels()

Examples

# GET: retrieve all variable labels
var_label(survey_data)

# GET: specific variables
var_label(survey_data, age, gender)

# GET: from a single vector
var_label(survey_data$age)

# SET: assign labels
data <- var_label(survey_data,
  age = "Age of respondent",
  gender = "Gender identity"
)

# REMOVE: set to NULL
data <- var_label(data, age = NULL)


Measure Population-Representative Spread (IQR)

Description

w_iqr() calculates the interquartile range using survey weights. The IQR is the distance between the 25th and 75th percentiles – it tells you the range that contains the middle 50% of your population. Unlike the standard deviation, the IQR is not affected by outliers, making it a robust measure of spread.

Usage

w_iqr(data, ..., weights = NULL, na.rm = TRUE)

Arguments

data

Your survey data (a data frame or tibble)

...

The numeric variables you want to analyze. You can list multiple variables or use helpers like starts_with("income")

weights

Survey weights to make results representative of your population. Without weights, you get the simple sample IQR.

na.rm

Remove missing values before calculating? (Default: TRUE)

Details

Understanding the Results

The IQR is especially useful when your data is skewed. For example, with income data, the IQR gives a better sense of "typical spread" than the SD because extreme incomes do not distort it.

When to Use This

Use w_iqr() when:

Formula

IQR_w = Q_{3,w} - Q_{1,w}

where Q_{1,w} and Q_{3,w} are the weighted 25th and 75th percentiles, calculated using cumulative weights (see w_quantile).

Value

Population-weighted IQR(s) with sample size information, including the weighted IQR, effective sample size (effective N), and the number of valid observations used.

References

IBM Corp. (2023). IBM SPSS Statistics 29 Algorithms. IBM Corporation.

See Also

IQR for the base R IQR function.

w_quantile for arbitrary weighted percentiles.

w_sd for weighted standard deviation (another spread measure).

w_range for the full weighted range.

describe for comprehensive descriptive statistics including IQR.

Validation status

Unweighted values use quantile Type 6 (SPSS HAVERAGE). Weighted values apply the HAVERAGE position to cumulative weights with linear interpolation - an R-internal extension (Tier 4 of the Validation Charter); SPSS reference validation for weighted percentiles is pending.

Other weighted_statistics: w_kurtosis(), w_mean(), w_median(), w_modus(), w_quantile(), w_range(), w_sd(), w_se(), w_skew(), w_var()

Examples

# Load required packages and data
library(dplyr)
data(survey_data)

# Basic weighted IQR
survey_data %>% w_iqr(age, weights = sampling_weight)

# Multiple variables
survey_data %>% w_iqr(age, income, weights = sampling_weight)

# Grouped data
survey_data %>% group_by(region) %>% w_iqr(age, weights = sampling_weight)

# In summarise context
survey_data %>% summarise(iqr_age = w_iqr(age, weights = sampling_weight))

# Unweighted (for comparison)
survey_data %>% w_iqr(age)


Measure Population-Representative Kurtosis

Description

w_kurtosis() measures how heavy the tails of your data's distribution are, using survey weights for population-representative results. Kurtosis tells you whether your data has unusually many extreme values (outliers) compared to a normal distribution:

Usage

w_kurtosis(data, ..., weights = NULL, na.rm = TRUE, excess = TRUE)

Arguments

data

Your survey data (a data frame or tibble)

...

The numeric variables you want to analyze. You can list multiple variables or use helpers like starts_with("trust")

weights

Survey weights to make results representative of your population. Without weights, you get the simple sample kurtosis.

na.rm

Remove missing values before calculating? (Default: TRUE)

excess

Show excess kurtosis? (Default: TRUE, matching SPSS). Excess kurtosis subtracts 3 so that a normal distribution has kurtosis of 0, making interpretation easier.

Details

Understanding the Results

Kurtosis is often checked together with skewness to assess normality. Both should be close to zero for normally distributed data.

When to Use This

Use w_kurtosis() when:

Formula

Uses the SPSS Type 2 (sample-corrected) excess kurtosis formula. First, the population excess kurtosis (g_2) is calculated:

g_2 = \frac{m_4}{m_2^2} - 3

where m_2 = \sum w_i(x_i - \bar{x}_w)^2 / V_1 and m_4 = \sum w_i(x_i - \bar{x}_w)^4 / V_1 with V_1 = \sum w_i.

Then, the bias-corrected (Type 2) kurtosis is:

G_2 = \frac{(n+1) \cdot g_2 + 6}{(n-2)(n-3)} \cdot (n-1)

where n = V_1 for weighted data.

Value

Population-weighted kurtosis value(s) with sample size information, including the weighted kurtosis, effective sample size (effective N), and the number of valid observations used.

References

Joanes, D. N., & Gill, C. A. (1998). Comparing measures of sample skewness and kurtosis. The Statistician, 47(1), 183-189.

IBM Corp. (2023). IBM SPSS Statistics 29 Algorithms. IBM Corporation.

See Also

w_skew for weighted skewness (distribution asymmetry).

describe for comprehensive descriptive statistics including kurtosis.

Other weighted_statistics: w_iqr(), w_mean(), w_median(), w_modus(), w_quantile(), w_range(), w_sd(), w_se(), w_skew(), w_var()

Examples

# Load required packages and data
library(dplyr)
data(survey_data)

# Basic weighted kurtosis (excess kurtosis, default)
survey_data %>% w_kurtosis(age, weights = sampling_weight)

# Multiple variables
survey_data %>% w_kurtosis(age, income, life_satisfaction, weights = sampling_weight)

# Grouped data
survey_data %>% group_by(region) %>% w_kurtosis(age, weights = sampling_weight)

# Raw kurtosis (not excess)
survey_data %>% w_kurtosis(age, weights = sampling_weight, excess = FALSE)

# In summarise context
survey_data %>% summarise(kurt_age = w_kurtosis(age, weights = sampling_weight))

# Unweighted (for comparison)
survey_data %>% w_kurtosis(age)


Calculate Population-Representative Averages

Description

w_mean() calculates averages that accurately represent your population by using survey weights. This ensures that groups who were over- or under-sampled contribute appropriately to the final average.

Usage

w_mean(data, ..., weights = NULL, na.rm = TRUE)

Arguments

data

Your survey data (a data frame or tibble)

...

The numeric variables you want to average. You can list multiple variables or use helpers like starts_with("income")

weights

Survey weights to make the average representative of your population. Without weights, you get the simple sample average.

na.rm

Remove missing values before calculating? (Default: TRUE)

Details

When to Use This

Use w_mean() when your survey uses sampling weights and you need population-representative averages. Weights correct for:

Understanding the Results

Formula

\bar{x}_w = \frac{\sum w_i \cdot x_i}{\sum w_i}

The effective sample size is: n_{eff} = (\sum w_i)^2 / \sum w_i^2

Value

Population-weighted average(s) with sample size information

References

IBM Corp. (2023). IBM SPSS Statistics 29 Algorithms. IBM Corporation.

See Also

weighted.mean for the base R weighted mean function.

w_sd for weighted standard deviation.

w_median for weighted median.

describe for comprehensive descriptive statistics.

Other weighted_statistics: w_iqr(), w_kurtosis(), w_median(), w_modus(), w_quantile(), w_range(), w_sd(), w_se(), w_skew(), w_var()

Examples

# Load required packages and data
library(dplyr)
data(survey_data)

# Basic weighted usage
survey_data %>% w_mean(age, weights = sampling_weight)

# Multiple variables
survey_data %>% w_mean(age, income, life_satisfaction, weights = sampling_weight)

# Grouped data
survey_data %>% group_by(region) %>% w_mean(age, weights = sampling_weight)

# In summarise context
survey_data %>% summarise(mean_age = w_mean(age, weights = sampling_weight))

# Unweighted (for comparison)
survey_data %>% w_mean(age)


Find the Population-Representative Middle Value

Description

w_median() finds the median (middle value) of your data using survey weights. The weighted median is the value where half the population falls below and half falls above. Unlike the mean, the median is not pulled by extreme values, making it a robust measure of the "typical" value in your population.

Usage

w_median(data, ..., weights = NULL, na.rm = TRUE)

Arguments

data

Your survey data (a data frame or tibble)

...

The numeric variables you want to analyze. You can list multiple variables or use helpers like starts_with("income")

weights

Survey weights to make results representative of your population. Without weights, you get the simple sample median.

na.rm

Remove missing values before calculating? (Default: TRUE)

Details

Understanding the Results

Comparing the weighted median to the weighted mean is informative:

When to Use This

Use w_median() when:

Formula

The weighted median is the weighted 50th percentile, computed with the SPSS HAVERAGE (quantile Type 6) position h = 0.5 * (W + 1) on the cumulative weights, with linear interpolation between bracketing observations. It is identical to w_quantile(x, probs = 0.5) by construction. Unweighted values match SPSS FREQUENCIES; weighted values with non-integer weights are an R-internal extension of the HAVERAGE rule (Tier 4 of the Validation Charter) pending SPSS reference runs.

Value

Population-weighted median(s) with sample size information, including the weighted median, effective sample size (effective N), and the number of valid observations used.

References

IBM Corp. (2023). IBM SPSS Statistics 29 Algorithms. IBM Corporation.

See Also

median for the base R median function.

w_mean for weighted means.

w_quantile for arbitrary weighted percentiles.

describe for comprehensive descriptive statistics including the median.

Other weighted_statistics: w_iqr(), w_kurtosis(), w_mean(), w_modus(), w_quantile(), w_range(), w_sd(), w_se(), w_skew(), w_var()

Examples

# Load required packages and data
library(dplyr)
data(survey_data)

# Basic weighted median
survey_data %>% w_median(age, weights = sampling_weight)

# Multiple variables
survey_data %>% w_median(age, income, weights = sampling_weight)

# Grouped data
survey_data %>% group_by(region) %>% w_median(age, weights = sampling_weight)

# In summarise context
survey_data %>% summarise(med_age = w_median(age, weights = sampling_weight))

# Unweighted (for comparison)
survey_data %>% w_median(age)


Find the Most Common Value in Your Population

Description

w_modus() finds the mode (most frequently occurring value) of your data using survey weights for population-representative results. The mode tells you which category or value is the most common in your population. This is especially useful for categorical variables (e.g., the most common education level, the most frequent employment status).

Unlike mean and median, the mode works with both numeric and categorical data.

Usage

w_modus(data, ..., weights = NULL, na.rm = TRUE)

Arguments

data

Your survey data (a data frame or tibble)

...

The variables you want to analyze. Works best with categorical or discrete numeric variables. You can list multiple variables or use helpers like starts_with("trust")

weights

Survey weights to make results representative of your population. Without weights, the mode is simply the most frequent value in your sample.

na.rm

Remove missing values before calculating? (Default: TRUE)

Details

Understanding the Results

If multiple values share the highest weighted frequency (ties), the first value encountered is returned.

When to Use This

Use w_modus() when:

Formula

The weighted mode is the value x_k that maximizes the total weight:

\text{Mode}_w = \arg\max_{x_k} \sum_{i: x_i = x_k} w_i

In other words, sum the weights for each unique value and pick the value with the largest total weight.

Value

Population-weighted mode(s) with sample size information, including the most common value (by weighted frequency), effective sample size (effective N), and the number of valid observations used.

References

IBM Corp. (2023). IBM SPSS Statistics 29 Algorithms. IBM Corporation.

See Also

w_median for the weighted middle value.

w_mean for weighted means.

frequency for complete frequency tables of categorical variables.

describe for comprehensive descriptive statistics including the mode.

Other weighted_statistics: w_iqr(), w_kurtosis(), w_mean(), w_median(), w_quantile(), w_range(), w_sd(), w_se(), w_skew(), w_var()

Examples

# Load required packages and data
library(dplyr)
data(survey_data)

# Basic weighted mode (most frequent value)
survey_data %>% w_modus(gender, weights = sampling_weight)

# Multiple variables (works best with categorical/discrete data)
survey_data %>% w_modus(gender, region, weights = sampling_weight)

# Grouped data
survey_data %>% group_by(region) %>% w_modus(gender, weights = sampling_weight)

# In summarise context
survey_data %>% summarise(mode_gender = w_modus(gender, weights = sampling_weight))

# Unweighted (for comparison)
survey_data %>% w_modus(gender)

Calculate Population-Representative Percentiles

Description

w_quantile() calculates percentiles (quantiles) using survey weights for population-representative results. Percentiles divide your data into equal portions – for example, the 25th percentile is the value below which 25% of your population falls. This is essential for understanding the distribution of variables like income, age, or satisfaction scores.

Usage

w_quantile(
  data,
  ...,
  weights = NULL,
  probs = c(0, 0.25, 0.5, 0.75, 1),
  na.rm = TRUE
)

Arguments

data

Your survey data (a data frame or tibble)

...

The numeric variables you want to analyze. You can list multiple variables or use helpers like starts_with("income")

weights

Survey weights to make results representative of your population. Without weights, you get the simple sample quantiles.

probs

Which percentiles to calculate, as proportions between 0 and 1. Default: c(0, 0.25, 0.5, 0.75, 1) for the minimum, 25th percentile, median, 75th percentile, and maximum. Use c(0.1, 0.5, 0.9) for deciles, or c(0.25, 0.5, 0.75) for quartiles only.

na.rm

Remove missing values before calculating? (Default: TRUE)

Details

Understanding the Results

Common percentiles and their meaning:

When to Use This

Use w_quantile() when:

Formula

Weighted quantiles are calculated using cumulative weights. Observations are sorted by value, weights are accumulated, and the requested percentile is found by linear interpolation at the point where the cumulative weight proportion reaches the target probability.

Value

Population-weighted quantile(s) with sample size information, including the weighted percentile values, effective sample size (effective N), and the number of valid observations used.

References

IBM Corp. (2023). IBM SPSS Statistics 29 Algorithms. IBM Corporation.

See Also

quantile for the base R quantile function.

w_median for the weighted median (50th percentile).

w_iqr for the weighted interquartile range (Q3 - Q1).

describe for comprehensive descriptive statistics including quantiles.

Validation status

Unweighted values use quantile Type 6 (SPSS HAVERAGE). Weighted values apply the HAVERAGE position to cumulative weights with linear interpolation - an R-internal extension (Tier 4 of the Validation Charter); SPSS reference validation for weighted percentiles is pending.

Other weighted_statistics: w_iqr(), w_kurtosis(), w_mean(), w_median(), w_modus(), w_range(), w_sd(), w_se(), w_skew(), w_var()

Examples

# Load required packages and data
library(dplyr)
data(survey_data)

# Basic weighted quantiles (0%, 25%, 50%, 75%, 100%)
survey_data %>% w_quantile(age, weights = sampling_weight)

# Custom quantiles
survey_data %>% w_quantile(income, weights = sampling_weight, probs = c(0.1, 0.5, 0.9))

# Multiple variables
survey_data %>% w_quantile(age, income, weights = sampling_weight)

# Grouped data
survey_data %>% group_by(region) %>% w_quantile(age, weights = sampling_weight)

# Unweighted (for comparison)
survey_data %>% w_quantile(age)


Find the Range of Your Data

Description

w_range() calculates the range (maximum minus minimum) of your data. The range gives you the total spread from the smallest to the largest observed value. It provides the w_* interface for consistency with other weighted statistics, though the range itself is not affected by weights (the minimum and maximum values remain the same regardless of weighting).

Usage

w_range(data, ..., weights = NULL, na.rm = TRUE)

Arguments

data

Your survey data (a data frame or tibble)

...

The numeric variables you want to analyze. You can list multiple variables or use helpers like starts_with("income")

weights

Survey weights are accepted for interface consistency, but do not affect the range calculation. The range depends only on the observed minimum and maximum values.

na.rm

Remove missing values before calculating? (Default: TRUE)

Details

Understanding the Results

Note: The range is sensitive to outliers. A single extreme value can dramatically increase the range. Consider using w_iqr for a more robust measure of spread.

When to Use This

Use w_range() when:

Formula

Range = \max(x) - \min(x)

Note: This statistic is weight-invariant. The minimum and maximum observed values do not change when weights are applied.

Value

The range (max - min) with sample size information, including the effective sample size (effective N) when weights are provided, and the number of valid observations used.

References

IBM Corp. (2023). IBM SPSS Statistics 29 Algorithms. IBM Corporation.

See Also

range for the base R range function.

w_iqr for the weighted interquartile range (more robust).

w_sd for weighted standard deviation (another spread measure).

describe for comprehensive descriptive statistics including range.

Other weighted_statistics: w_iqr(), w_kurtosis(), w_mean(), w_median(), w_modus(), w_quantile(), w_sd(), w_se(), w_skew(), w_var()

Examples

# Load required packages and data
library(dplyr)
data(survey_data)

# Basic range
survey_data %>% w_range(age, weights = sampling_weight)

# Multiple variables
survey_data %>% w_range(age, income, weights = sampling_weight)

# Grouped data
survey_data %>% group_by(region) %>% w_range(age, weights = sampling_weight)

# In summarise context
survey_data %>% summarise(range_age = w_range(age, weights = sampling_weight))

# Unweighted (for comparison)
survey_data %>% w_range(age)


Calculate Population-Representative Standard Deviations

Description

w_sd() calculates standard deviations that accurately represent your population by using survey weights. The standard deviation tells you how spread out your data is around the average – a larger SD means more variation in responses, while a smaller SD means responses cluster tightly around the mean.

Without weights, you describe spread in your sample only. With weights, you estimate how spread out values are in the entire population.

Usage

w_sd(data, ..., weights = NULL, na.rm = TRUE)

Arguments

data

Your survey data (a data frame or tibble)

...

The numeric variables you want to analyze. You can list multiple variables or use helpers like starts_with("trust")

weights

Survey weights to make results representative of your population. Without weights, you get the simple sample standard deviation.

na.rm

Remove missing values before calculating? (Default: TRUE)

Details

Understanding the Results

A large difference between weighted and unweighted SD suggests that the variability in your sample does not accurately reflect the population.

When to Use This

Use w_sd() when:

Formula

The weighted standard deviation uses the SPSS frequency weights formula:

s_w = \sqrt{\frac{\sum w_i (x_i - \bar{x}_w)^2}{V_1 - 1}}

where V_1 = \sum w_i is the sum of all weights and \bar{x}_w = \sum w_i x_i / V_1 is the weighted mean.

The effective sample size is: n_{eff} = (\sum w_i)^2 / \sum w_i^2

Value

Population-weighted standard deviation(s) with sample size information, including the weighted SD, effective sample size (effective N), and the number of valid observations used.

References

IBM Corp. (2023). IBM SPSS Statistics 29 Algorithms. IBM Corporation.

See Also

sd for the base R standard deviation function.

w_var for weighted variance (the square of weighted SD).

w_mean for weighted means.

describe for comprehensive descriptive statistics including SD.

Other weighted_statistics: w_iqr(), w_kurtosis(), w_mean(), w_median(), w_modus(), w_quantile(), w_range(), w_se(), w_skew(), w_var()

Examples

# Load required packages and data
library(dplyr)
data(survey_data)

# Basic weighted standard deviation
survey_data %>% w_sd(age, weights = sampling_weight)

# Multiple variables
survey_data %>% w_sd(age, income, life_satisfaction, weights = sampling_weight)

# Grouped data
survey_data %>% group_by(region) %>% w_sd(age, weights = sampling_weight)

# In summarise context
survey_data %>% summarise(sd_age = w_sd(age, weights = sampling_weight))

# Unweighted (for comparison)
survey_data %>% w_sd(age)


Calculate Population-Representative Standard Errors

Description

w_se() calculates the standard error of the mean using survey weights. The standard error tells you how precisely you have estimated the population mean – a smaller SE means your estimate is more precise. This is essential for constructing confidence intervals and assessing the reliability of your weighted mean estimates.

Usage

w_se(data, ..., weights = NULL, na.rm = TRUE)

Arguments

data

Your survey data (a data frame or tibble)

...

The numeric variables you want to analyze. You can list multiple variables or use helpers like starts_with("trust")

weights

Survey weights to make results representative of your population. Without weights, you get the simple sample standard error.

na.rm

Remove missing values before calculating? (Default: TRUE)

Details

Understanding the Results

When to Use This

Use w_se() when:

Formula

The weighted standard error is calculated as:

SE_w = \frac{s_w}{\sqrt{V_1}}

where s_w is the weighted standard deviation (see w_sd) and V_1 = \sum w_i is the sum of all weights.

For the unweighted case: SE = s / \sqrt{n}

Value

Population-weighted standard error(s) with sample size information, including the weighted SE, effective sample size (effective N), and the number of valid observations used.

References

IBM Corp. (2023). IBM SPSS Statistics 29 Algorithms. IBM Corporation.

See Also

w_sd for weighted standard deviation.

w_mean for weighted means.

describe for comprehensive descriptive statistics including SE.

Other weighted_statistics: w_iqr(), w_kurtosis(), w_mean(), w_median(), w_modus(), w_quantile(), w_range(), w_sd(), w_skew(), w_var()

Examples

# Load required packages and data
library(dplyr)
data(survey_data)

# Basic weighted standard error
survey_data %>% w_se(age, weights = sampling_weight)

# Multiple variables
survey_data %>% w_se(age, income, weights = sampling_weight)

# Grouped data
survey_data %>% group_by(region) %>% w_se(age, weights = sampling_weight)

# In summarise context
survey_data %>% summarise(se_age = w_se(age, weights = sampling_weight))

# Unweighted (for comparison)
survey_data %>% w_se(age)


Measure Population-Representative Skewness

Description

w_skew() measures how asymmetric your data's distribution is, using survey weights for population-representative results. Skewness tells you whether values tend to trail off more to the left or right:

Usage

w_skew(data, ..., weights = NULL, na.rm = TRUE)

Arguments

data

Your survey data (a data frame or tibble)

...

The numeric variables you want to analyze. You can list multiple variables or use helpers like starts_with("trust")

weights

Survey weights to make results representative of your population. Without weights, you get the simple sample skewness.

na.rm

Remove missing values before calculating? (Default: TRUE)

Details

Understanding the Results

High skewness suggests you might want to use the median instead of the mean as a measure of center, and non-parametric tests instead of t-tests.

When to Use This

Use w_skew() when:

Formula

Uses the SPSS Type 2 (sample-corrected) skewness formula. First, the population skewness (g_1) is calculated:

g_1 = \frac{m_3}{m_2^{3/2}}

where m_2 = \sum w_i(x_i - \bar{x}_w)^2 / V_1 and m_3 = \sum w_i(x_i - \bar{x}_w)^3 / V_1 with V_1 = \sum w_i.

Then, the bias-corrected (Type 2) skewness is:

G_1 = g_1 \cdot \frac{\sqrt{n(n-1)}}{n-2}

where n = V_1 for weighted data.

Value

Population-weighted skewness value(s) with sample size information, including the weighted skewness, effective sample size (effective N), and the number of valid observations used.

References

Joanes, D. N., & Gill, C. A. (1998). Comparing measures of sample skewness and kurtosis. The Statistician, 47(1), 183-189.

IBM Corp. (2023). IBM SPSS Statistics 29 Algorithms. IBM Corporation.

See Also

w_kurtosis for weighted kurtosis (tail heaviness).

describe for comprehensive descriptive statistics including skewness.

Other weighted_statistics: w_iqr(), w_kurtosis(), w_mean(), w_median(), w_modus(), w_quantile(), w_range(), w_sd(), w_se(), w_var()

Examples

# Load required packages and data
library(dplyr)
data(survey_data)

# Basic weighted skewness
survey_data %>% w_skew(age, weights = sampling_weight)

# Multiple variables
survey_data %>% w_skew(age, income, life_satisfaction, weights = sampling_weight)

# Grouped data
survey_data %>% group_by(region) %>% w_skew(age, weights = sampling_weight)

# In summarise context
survey_data %>% summarise(skew_age = w_skew(age, weights = sampling_weight))

# Unweighted (for comparison)
survey_data %>% w_skew(age)


Calculate Population-Representative Variance

Description

w_var() calculates variance that accurately represents your population by using survey weights. Variance measures how far values spread out from the average – it is the square of the standard deviation. A larger variance means more dispersion in your population's responses.

Without weights, you describe the spread in your sample only. With weights, you estimate how spread out values are in the entire population.

Usage

w_var(data, ..., weights = NULL, na.rm = TRUE)

Arguments

data

Your survey data (a data frame or tibble)

...

The numeric variables you want to analyze. You can list multiple variables or use helpers like starts_with("trust")

weights

Survey weights to make results representative of your population. Without weights, you get the simple sample variance.

na.rm

Remove missing values before calculating? (Default: TRUE)

Details

Understanding the Results

When to Use This

Use w_var() when:

For reporting purposes, w_sd is usually preferred because the standard deviation is in the same units as the original variable.

Formula

The weighted variance uses the SPSS frequency weights formula:

s^2_w = \frac{\sum w_i (x_i - \bar{x}_w)^2}{V_1 - 1}

where V_1 = \sum w_i is the sum of all weights and \bar{x}_w = \sum w_i x_i / V_1 is the weighted mean.

Note: s^2_w = (s_w)^2, i.e., the weighted variance is the square of the weighted standard deviation.

Value

Population-weighted variance(s) with sample size information, including the weighted variance, effective sample size (effective N), and the number of valid observations used.

References

IBM Corp. (2023). IBM SPSS Statistics 29 Algorithms. IBM Corporation.

See Also

var for the base R variance function.

w_sd for weighted standard deviation (the square root of variance).

w_mean for weighted means.

describe for comprehensive descriptive statistics including variance.

Other weighted_statistics: w_iqr(), w_kurtosis(), w_mean(), w_median(), w_modus(), w_quantile(), w_range(), w_sd(), w_se(), w_skew()

Examples

# Load required packages and data
library(dplyr)
data(survey_data)

# Basic weighted variance
survey_data %>% w_var(age, weights = sampling_weight)

# Multiple variables
survey_data %>% w_var(age, income, weights = sampling_weight)

# Grouped data
survey_data %>% group_by(region) %>% w_var(age, weights = sampling_weight)

# In summarise context
survey_data %>% summarise(var_age = w_var(age, weights = sampling_weight))

# Unweighted (for comparison)
survey_data %>% w_var(age)


Compare Two Related Measurements Without Assuming Normality

Description

wilcoxon_test() compares two paired measurements from the same subjects when your data isn't normally distributed. It's the non-parametric alternative to the paired t-test.

Think of it as:

The test tells you:

Usage

wilcoxon_test(data, x, y, weights = NULL, conf.level = 0.95)

Arguments

data

Your survey data (a data frame or tibble) in wide format, with one row per subject and the two measurements in separate columns

x

The first measurement variable (e.g., pre-test, trust in government)

y

The second measurement variable (e.g., post-test, trust in media). The difference is computed as y - x

weights

Optional survey weights for population-representative results

conf.level

Confidence level for intervals (Default: 0.95 = 95 percent)

Details

Understanding the Results

P-value: If p < 0.05, the two measurements are significantly different

Effect Size r (How strong is the difference?):

Rank Categories:

When to Use This

Use Wilcoxon signed-rank test when:

Relationship to Other Tests

Weighted variants

SPSS NPAR TESTS ignores WEIGHT BY, so weighted results have no SPSS reference. The weighted variant is an R-only frequency-weight extension that reduces exactly to the unweighted test when all weights equal 1 (enforced by an internal invariance suite); see vignette("spss-compatibility") for validation status.

Value

Test results showing whether the two measurements differ, including:

References

Wilcoxon, F. (1945). Individual comparisons by ranking methods. Biometrics Bulletin, 1(6), 80-83.

Fritz, C. O., Morris, P. E., & Richler, J. J. (2012). Effect size estimates: current use, calculations, and interpretation. Journal of Experimental Psychology: General, 141(1), 2.

See Also

wilcox.test for the base R Wilcoxon test.

mann_whitney for comparing two independent groups.

Other hypothesis_tests: ancova(), binomial_test(), chi_square(), chisq_gof(), factorial_anova(), fisher_test(), friedman_test(), kruskal_wallis(), mann_whitney(), mcnemar_test(), oneway_anova(), t_test()

Examples

# Load required packages and data
library(dplyr)
data(survey_data)

# Compare trust in government vs trust in media
survey_data %>%
  wilcoxon_test(x = trust_government, y = trust_media)

# Weighted analysis
survey_data %>%
  wilcoxon_test(x = trust_government, y = trust_media,
                weights = sampling_weight)

# Grouped analysis (separate test per region)
survey_data %>%
  group_by(region) %>%
  wilcoxon_test(x = trust_government, y = trust_media)


Export Data to SPSS Format

Description

Writes a data frame to an SPSS .sav file, preserving variable labels, value labels, and user-defined missing values. When exporting data that was imported with read_spss() (with tag_na = TRUE), the tagged NAs are automatically converted back to SPSS user-defined missing values, enabling full roundtrip fidelity.

Usage

write_spss(data, path, compress = c("byte", "none", "zsav"))

Arguments

data

A data frame to export. Columns of class haven_labelled will have their labels and missing value metadata written to the .sav file.

path

Path to the output file. Must end in .sav or .zsav.

compress

Compression type. One of "byte" (default, byte-level compression), "none" (no compression), or "zsav" (zlib compression, requires SPSS v21+).

Details

Tagged NA Roundtripping

Data imported via read_spss() stores SPSS user-defined missing values as tagged NAs with an na_tag_map attribute mapping tag characters to original codes (e.g., -9, -8). write_spss() reverses this process: tagged NAs are converted back to their original numeric codes, and the SPSS user-defined missing value specification is reconstructed so that the exported .sav file has the same missing value definitions as the original.

Cross-Format Export

When exporting data originally imported from Stata or SAS (with native extended missing values like .a-.z or .A-.Z), these cannot be represented as SPSS user-defined missing values. In this case, they are written as system missing (regular NA) with a warning.

When to Use This

Use write_spss() when you:

Value

Invisibly returns the file path.

See Also

read_spss() for importing SPSS files, write_xlsx() for Excel export, write_stata() for Stata export, write_xpt() for SAS transport export, untag_na(), strip_tags()

Other data-export: write_stata(), write_xlsx(), write_xpt()

Examples


if (requireNamespace("haven", quietly = TRUE)) {
  # Roundtrip: write to a temporary .sav, read back
  tmp <- tempfile(fileext = ".sav")
  write_spss(survey_data, tmp)
  data <- read_spss(tmp)

  # Export with zlib compression (smaller file, requires SPSS v21+)
  tmp_z <- tempfile(fileext = ".zsav")
  write_spss(survey_data, tmp_z, compress = "zsav")

  unlink(c(tmp, tmp_z))
}



Export Data to Stata Format

Description

Writes a data frame to a Stata .dta file, preserving variable labels, value labels, and missing value types. Tagged NAs from any source format (SPSS, Stata, SAS) are written as Stata extended missing values (.a through .z).

Usage

write_stata(data, path, version = 14)

Arguments

data

A data frame to export. Columns of class haven_labelled will have their labels written to the .dta file.

path

Path to the output file. Must end in .dta.

version

Stata file version to use. Supported values: 8-15. Default is 14 (Stata 14/15, supports Unicode). Use 13 for compatibility with older Stata versions.

Details

Tagged NA Handling

Stata natively supports 27 extended missing values: .a through .z and . (system missing). When exporting data with tagged NAs:

Limitations

Stata supports at most 27 distinct missing types per variable. SPSS data with more than 27 tagged NA types in a single variable may lose some distinctions (though this is extremely rare in practice).

Value

Invisibly returns the file path.

See Also

read_stata() for importing Stata files, write_spss() for SPSS export, write_xlsx() for Excel export, write_xpt() for SAS transport export

Other data-export: write_spss(), write_xlsx(), write_xpt()

Examples


if (requireNamespace("haven", quietly = TRUE)) {
  # Roundtrip: write to a temporary .dta, read back
  tmp <- tempfile(fileext = ".dta")
  write_stata(survey_data, tmp)
  data <- read_stata(tmp)

  # Stata 13 compatibility
  tmp13 <- tempfile(fileext = ".dta")
  write_stata(survey_data, tmp13, version = 13)

  unlink(c(tmp, tmp13))
}



Export Data to Excel with Label Support

Description

Writes data to an Excel (.xlsx) file with support for variable labels, value labels, and tagged NA metadata. When exporting labelled survey data, a "Labels" reference sheet is automatically included so that reviewers can look up what each numeric code means – even without R access.

Three input types are supported:

  1. Data frame: Exports the data plus a "Labels" reference sheet with variable labels, value labels, and missing value codes.

  2. Codebook object: Exports the codebook as it appears in the HTML viewer – with values, value labels, and frequencies stacked inside each cell, tagged NAs separated by a line, and an overview sheet with dataset metadata.

  3. Named list: Each list element becomes a separate sheet. Elements can be data frames, frequency() results, or codebook() results – types can be mixed freely. For data frame elements, a combined "Labels" sheet is appended.

Usage

write_xlsx(x, file, ...)

## S3 method for class 'frequency'
write_xlsx(x, file, overwrite = TRUE, ...)

Arguments

x

Object to export: a data frame, a codebook() result, or a named list of data frames.

file

Path to the output .xlsx file. Must end in .xlsx.

...

Additional arguments passed to methods:

labels

(data.frame and list methods) Include a "Labels" reference sheet? Default: TRUE

frequencies

(codebook method) Include per-variable frequency sheets? Default: FALSE

overwrite

Overwrite existing file? Default: TRUE.

Details

Data Frame Export

The "Labels" sheet provides a complete lookup table for all variable and value labels in your data, structured in long format. The "Type" column distinguishes between regular value labels ("valid") and tagged missing value labels ("missing"), making it easy to filter in Excel.

Data values are written as their underlying numeric or character codes (not as label text), preserving the original coding scheme.

Codebook Export

The codebook export reproduces the HTML codebook layout: each variable occupies one row, with values, value labels, and frequencies stacked within their cells using line breaks. Tagged NAs are shown below a separator line, matching the visual style of codebook() in the RStudio Viewer.

When to Use This

Use write_xlsx() when you:

Value

Invisibly returns the file path.

Methods (by class)

See Also

codebook() for generating codebook objects, frequency() for frequency tables, read_spss(), read_por(), read_stata(), read_sas(), read_xpt(), read_xlsx() for importing labelled data

Other data-export: write_spss(), write_stata(), write_xpt()

Examples


if (requireNamespace("openxlsx2", quietly = TRUE)) {
  # Export data with automatic label reference sheet
  tmp <- tempfile(fileext = ".xlsx")
  write_xlsx(survey_data, tmp)

  # Export a codebook (reproduces HTML layout in Excel)
  tmp_cb <- tempfile(fileext = ".xlsx")
  codebook(survey_data) |> write_xlsx(tmp_cb)

  # Export frequency tables
  tmp_freq <- tempfile(fileext = ".xlsx")
  frequency(survey_data, gender) |> write_xlsx(tmp_freq)

  # Multi-sheet export (mixed types: data frames, frequencies, codebooks)
  tmp_multi <- tempfile(fileext = ".xlsx")
  write_xlsx(
    list(
      "Frequencies" = frequency(survey_data, gender, life_satisfaction),
      "Codebook"    = codebook(survey_data),
      "Data"        = survey_data
    ),
    tmp_multi
  )

  unlink(c(tmp, tmp_cb, tmp_freq, tmp_multi))
}



if (requireNamespace("openxlsx2", quietly = TRUE)) {
  # Single variable
  tmp <- tempfile(fileext = ".xlsx")
  frequency(survey_data, gender) |> write_xlsx(tmp)

  # Multiple variables on one sheet
  tmp2 <- tempfile(fileext = ".xlsx")
  frequency(survey_data, gender, life_satisfaction, region) |>
    write_xlsx(tmp2)

  unlink(c(tmp, tmp2))
}



Export Data to SAS Transport Format

Description

Writes a data frame to a SAS transport file (.xpt), preserving variable labels and missing value types. Tagged NAs from any source format (SPSS, Stata, SAS) are written as SAS special missing values (.A through .Z, ._).

Usage

write_xpt(data, path, version = 5, name = NULL)

Arguments

data

A data frame to export.

path

Path to the output file. Must end in .xpt.

version

SAS transport file version. Either 5 (default, SAS Transport v5, most compatible) or 8 (SAS Transport v8, supports longer variable names).

name

Member name for the dataset within the transport file. If NULL, derived from the file name. Maximum 8 characters for version 5.

Details

Tagged NA Handling

SAS supports 28 special missing values: . (system missing), .A through .Z, and ._. When exporting data with tagged NAs:

Limitations

SAS transport files do not store value labels. If your data has value labels, consider using write_spss() or write_xlsx() instead, which preserve full label metadata. Variable labels are preserved.

Value

Invisibly returns the file path.

See Also

read_xpt() and read_sas() for importing SAS files, write_spss() for SPSS export, write_stata() for Stata export, write_xlsx() for Excel export

Other data-export: write_spss(), write_stata(), write_xlsx()

Examples


if (requireNamespace("haven", quietly = TRUE)) {
  # Roundtrip: write to a temporary .xpt transport file, read back
  tmp <- tempfile(fileext = ".xpt")
  write_xpt(survey_data, tmp)
  data <- read_xpt(tmp)

  unlink(tmp)
}