Type: Package
Title: APA 7th Edition Statistical Tables, Plots, and Multilevel Model Reports
Version: 0.1.0
Description: Produces publication-ready statistical tables and figures formatted according to the 7th edition of the American Psychological Association (APA) style guidelines. Supports descriptive statistics, t-tests, z-tests, chi-square tests, Analysis of Variance (ANOVA), Analysis of Covariance (ANCOVA), two-way ANOVA with simple effects, Multivariate Analysis of Variance (MANOVA), robust and cluster-robust regression using Heteroscedasticity-Consistent (HC) standard errors, post-hoc pairwise comparisons, homoskedasticity and heteroscedasticity diagnostics including the Non-Constant Variance (NCV) test, proportion tests, and multilevel mixed-effects models with intraclass correlation coefficients (ICC) and model-comparison tables. Output can be directed to the console, Microsoft Word (via 'officer' and 'flextable'), or LaTeX. For APA style guidelines see American Psychological Association (2020, ISBN:978-1-4338-3216-1).
License: MIT + file LICENSE
Encoding: UTF-8
Language: en-US
LazyData: true
RoxygenNote: 7.3.3
Depends: R (≥ 4.1.0)
Imports: stats, utils, ggplot2 (≥ 3.4.0), rlang, emmeans (≥ 1.8.0), lme4 (≥ 1.1-30), lmtest (≥ 0.9-40), sandwich (≥ 3.0-0), car (≥ 3.1-0), officer (≥ 0.6.0), flextable (≥ 0.9.0)
Suggests: lmerTest (≥ 3.1-3), MuMIn (≥ 1.47.0), ggeffects (≥ 1.3.0), knitr, rmarkdown, testthat (≥ 3.0.0)
VignetteBuilder: knitr
URL: https://github.com/causalfragility-lab/statAPA
BugReports: https://github.com/causalfragility-lab/statAPA/issues
NeedsCompilation: no
Packaged: 2026-04-11 19:19:11 UTC; Subir
Author: Subir Hait ORCID iD [aut, cre]
Maintainer: Subir Hait <haitsubi@msu.edu>
Repository: CRAN
Date/Publication: 2026-04-16 18:30:02 UTC

ECLS_demo: Compact, simulated ECLS-K-style dataset

Description

A small, simulated, school-clustered dataset used in package examples and the vignette.

Usage

data(ECLS_demo)

Format

A data frame with 800 rows and 4 variables:

schid

School ID (integer, 1-20)

SES

Standardized socioeconomic status (numeric)

gender

Factor with levels Female, Male

math

Continuous math score (approx. mean 500, SD \approx 14)

Examples

data(ECLS_demo)
str(ECLS_demo)

APA 7-style Analysis of Covariance (ANCOVA) table with adjusted means

Description

Fits an Analysis of Covariance (ANCOVA) model and produces an APA-formatted table of the omnibus F-tests together with a second table of covariate-adjusted marginal means for the focal factor. Validates that the covariate(s) are continuous and not involved in an interaction with the focal factor (a key ANCOVA assumption).

Usage

apa_ancova(
  formula,
  data,
  covariate,
  focal,
  type = c("II", "III"),
  es = c("partial_eta2", "eta2", "omega2"),
  conf_level = 0.95,
  output = c("console", "word", "latex"),
  file = NULL,
  table_title = "ANCOVA Results"
)

Arguments

formula

A model formula, e.g. y ~ group + covariate or y ~ group + covariate1 + covariate2.

data

A data frame containing the variables in formula.

covariate

Character vector naming the covariate column(s) in data. Used for validation and labelling.

focal

Character scalar: the name of the focal (grouping) factor whose adjusted means will be reported.

type

Sums-of-squares type: "II" (default) or "III".

es

Effect size to report: "eta2", "partial_eta2" (default), or "omega2".

conf_level

Confidence level for adjusted-means intervals (default 0.95).

output

Output target: "console", "word", or "latex".

file

Path for Word output when output = "word".

table_title

Optional caption for the omnibus table (default "ANCOVA Results").

Details

Analysis of Covariance (ANCOVA) partitions variance in a continuous outcome into effects of a grouping factor and one or more continuous covariates, reducing error variance and yielding covariate-adjusted group comparisons. The adjusted means reported here are estimated marginal means (via emmeans) evaluated at the mean(s) of the covariate(s). Homogeneity of regression slopes (no covariate-by-group interaction) is assumed; this function warns if it detects an interaction term involving the covariate and the focal factor in the formula.

Value

Invisibly returns a list with elements:

model

The fitted lm object.

anova_table

A data.frame of the omnibus Analysis of Covariance (ANCOVA) results with columns Source, SS (Sum of Squares), df, MS (Mean Square), F, p, and the chosen effect-size column.

adjusted_means

A data.frame of covariate-adjusted marginal means for focal, from emmeans::emmeans(), with columns focal, Adjusted M (adjusted mean), SE, and 95% CI.

note

A character string with the APA-style table note.

The function is called primarily for its side effect of printing or writing the tables.

Examples

# ANCOVA: mpg ~ cyl (factor) + wt (covariate)
mtcars2 <- mtcars
mtcars2$cyl <- factor(mtcars2$cyl)
result <- apa_ancova(
  mpg ~ cyl + wt,
  data      = mtcars2,
  covariate = "wt",
  focal     = "cyl"
)
str(result$adjusted_means)

APA 7-style ANOVA / ANCOVA table (Type II/III) with effect sizes

Description

APA 7-style ANOVA / ANCOVA table (Type II/III) with effect sizes

Usage

apa_anova(
  model,
  data = NULL,
  type = c("II", "III"),
  es = c("eta2", "partial_eta2", "omega2"),
  output = c("console", "word", "latex"),
  file = NULL,
  table_title = "ANOVA Results"
)

Arguments

model

An lm/aov object or a formula with data.

data

Optional data if you pass a formula.

type

"II" or "III" (default "II").

es

Effect size to report: "eta2", "partial_eta2", or "omega2".

output

"console", "word", or "latex".

file

Path for Word output (when output = "word").

table_title

Optional caption title (default "ANOVA Results").

Value

Invisibly returns a list with two components:

anova

The full ANOVA table as returned by car::Anova(), including all rows.

table

A data.frame formatted for APA output, with columns Source, SS (Sum of Squares), df (degrees of freedom), MS (Mean Square), F (F-statistic), p (formatted p-value), and the chosen effect-size column (eta2, partial_eta2, or omega2).

When output = "latex", the list also contains a latex element with the LaTeX table string. The function is called primarily for its side effect of printing or writing the table.

Examples

fit <- lm(mpg ~ factor(cyl) + wt, data = mtcars)
result <- apa_anova(fit)
str(result$table)

APA chi-square test (goodness-of-fit or independence) with Cramer's V / phi

Description

APA chi-square test (goodness-of-fit or independence) with Cramer's V / phi

Usage

apa_chisq(
  x,
  p = NULL,
  correct = FALSE,
  simulate.p.value = FALSE,
  B = 2000,
  output = c("console", "list")
)

Arguments

x

Either a contingency table/matrix (independence test), or a vector of observed counts (goodness-of-fit test).

p

A vector of expected probabilities for goodness-of-fit (ignored for independence).

correct

Logical, Yates continuity correction for 2x2 tables (default FALSE).

simulate.p.value

Logical, use Monte Carlo simulation (passed to [stats::chisq.test]).

B

Number of replicates for simulation (passed to [stats::chisq.test]).

output

One of "console" or "list". "console" prints an APA-formatted summary to the console; "list" returns the result invisibly without printing.

Value

A list with two elements:

table

A data.frame with one row containing columns Test (test name), Stat (chi-square statistic), df (degrees of freedom), p (formatted p-value), Effect (name of effect size: "V" for Cramer's V or "phi" for the phi coefficient), and Value (the numeric effect-size estimate).

note

A character string with the APA-style table note.

Examples

# Independence test
m <- matrix(c(30, 10, 20, 40), nrow = 2)
apa_chisq(m)

# Goodness-of-fit test
apa_chisq(c(50, 30, 20), p = c(0.5, 0.3, 0.2))

APA 7-style descriptive statistics table

Description

APA 7-style descriptive statistics table

Usage

apa_descriptives(
  data,
  vars,
  group = NULL,
  digits = 2,
  output = c("console", "word", "latex"),
  file = NULL,
  table_title = NULL
)

Arguments

data

Data frame.

vars

Character vector of variable names to summarize.

group

Optional single grouping variable name in data.

digits

Decimals for means/SDs.

output

"console", "word", or "latex".

file

Path for Word output (when output = "word").

table_title

Optional caption; defaults to "Descriptive Statistics" or "Descriptive Statistics by group".

Value

Invisibly returns a list with two elements:

descriptives_df

A data.frame with one row per variable. Without grouping, columns are Variable, M (mean), SD (standard deviation), and N (number of non-missing observations). With grouping, there is one M (SD) column per group level plus a Total: M (SD) column and N.

note

A character string with the APA-style table note.

When output = "latex", the list additionally contains a latex element with the LaTeX table string. The function is called primarily for its side effect of printing or writing the table.

Examples

result <- apa_descriptives(mtcars, vars = c("mpg", "wt", "hp"))
str(result$descriptives_df)

result_grp <- apa_descriptives(mtcars, vars = c("mpg", "wt"),
                               group = "cyl")
str(result_grp$descriptives_df)

APA-Style Heteroscedasticity Diagnostics

Description

Runs a studentized Breusch-Pagan test (lmtest::bptest) and, if available, the Non-Constant Variance (NCV) test (car::ncvTest), and prints results in APA format.

Usage

apa_hetero(model, output = c("console", "word", "latex"), file = NULL)

Arguments

model

Fitted lm or glm object.

output

Output target: one of "console", "word", or "latex".

file

Path for Word output if output = "word".

Details

The Breusch-Pagan test examines whether the variance of residuals depends on fitted values. The Non-Constant Variance (NCV) test (if available via the car package) performs a similar check using a score test. Both are useful for detecting heteroscedasticity in regression models.

Value

Invisibly returns a data.frame of test results with columns:

Test

Name of the test run (e.g., "Breusch-Pagan", "Non-Constant Variance (NCV)").

Stat

The test statistic (formatted to 2 decimal places).

df

Degrees of freedom for the test statistic.

p

Formatted p-value string (e.g., "< .001").

Returns NULL invisibly if no tests could be computed. The function is called primarily for its side effect of printing or writing the table.

Examples

fit <- lm(mpg ~ wt + hp, data = mtcars)
result <- apa_hetero(fit)
str(result)


Homoskedasticity check (APA-style summary)

Description

Reports whether common tests fail to detect heteroskedasticity, i.e., results are consistent with homoskedastic errors. Internally runs Breusch-Pagan and White tests via lmtest. Optionally runs Levene/Brown-Forsythe via car if a grouping factor is supplied.

Usage

apa_homoskedasticity(
  model,
  group = NULL,
  center = c("mean", "median"),
  alpha = 0.05,
  output = c("console", "word", "latex"),
  file = NULL
)

Arguments

model

Fitted lm or glm object.

group

Optional grouping factor (for Levene/Brown-Forsythe). If provided, car::leveneTest will be attempted.

center

Character for Levene center, one of "mean" or "median". "median" yields Brown-Forsythe.

alpha

Significance level for the textual conclusion (default 0.05).

output

"console", "word", or "latex".

file

Path for Word output when output = "word".

Value

Invisibly returns a data.frame of test results with columns:

Test

Name of the test run (e.g., "Breusch-Pagan", "White (BP with fitted + fitted^2)", "Levene (mean)", or "Brown-Forsythe (Levene, median)").

Stat

The numeric test statistic.

df

Degrees of freedom (may be NA for some tests).

p

The raw p-value.

Returns NULL invisibly if no tests could be computed. The function is called primarily for its side effect of printing or writing the table.

Examples

fit <- lm(mpg ~ wt + cyl, data = mtcars)
result <- apa_homoskedasticity(fit, output = "console")
str(result)

APA 7-style Multivariate Analysis of Variance (MANOVA) table

Description

Runs a one-way or factorial Multivariate Analysis of Variance (MANOVA) and produces an APA-formatted summary table. Reports all four multivariate test statistics (Pillai's trace, Wilks' lambda, Hotelling-Lawley trace, and Roy's largest root) together with approximate F-statistics, degrees of freedom, p-values, and eta-squared effect sizes.

Usage

apa_manova(
  formula,
  data,
  type = c("II", "III"),
  output = c("console", "word", "latex"),
  file = NULL,
  table_title = "MANOVA Results"
)

Arguments

formula

A formula of the form cbind(y1, y2, ...) ~ x1 + x2. The left-hand side must use cbind() to bind the dependent variables.

data

A data frame containing the variables in formula.

type

Sums-of-squares type passed to car::Anova(): "II" (default) or "III".

output

Output target: "console", "word", or "latex".

file

Path for Word output when output = "word".

table_title

Optional caption (default "MANOVA Results").

Details

Multivariate Analysis of Variance (MANOVA) tests whether group means differ across a set of correlated dependent variables simultaneously. Pillai's trace is the most robust statistic and is recommended when assumptions may be violated. Wilks' lambda is the most commonly reported. Hotelling-Lawley trace and Roy's largest root are sensitive to a single large discriminant function. Effect sizes (eta-squared) are approximations based on the F-approximation degrees of freedom.

Value

Invisibly returns a list with elements:

manova

The raw manova model object.

summary

The summary list from summary.manova(), containing one element per test statistic ("Pillai", "Wilks", "Hotelling-Lawley", "Roy").

table

A data.frame formatted for APA output with columns Effect (predictor name), Test (statistic name), Stat (test statistic value), approx F, num df (numerator degrees of freedom), den df (denominator degrees of freedom), p (formatted p-value), and eta2 (eta-squared, computed as 1 - Wilks for Wilks' lambda, else as the ratio of the hypothesis sum of squares to total).

note

A character string with the APA-style table note.

The function is called primarily for its side effect of printing or writing the table.

Examples

# One-way MANOVA: sepal and petal length by species
result <- apa_manova(
  cbind(Sepal.Length, Petal.Length) ~ Species,
  data = iris
)
str(result$table)

APA 7-style multilevel model (mixed-effects) reporting table

Description

Produces APA-formatted tables for one or more multilevel models fitted with lme4. Reports fixed effects with confidence intervals, random effects (variances and standard deviations), the intraclass correlation coefficient (ICC), marginal and conditional R-squared (via MuMIn if available, else a manual approximation), and an optional likelihood ratio model comparison table. Supports random intercept, random slope, and cross-level interaction models.

Usage

apa_multilevel(
  ...,
  model_names = NULL,
  conf_level = 0.95,
  digits = 2,
  output = c("console", "word", "latex"),
  file = NULL,
  table_title = "Multilevel Model Results"
)

Arguments

...

One or more fitted lmerMod or glmerMod objects (from lme4). If more than one is supplied, a likelihood ratio model-comparison table is also printed.

model_names

Optional character vector of labels for the models (same length as ...). Defaults to "Model 1", "Model 2", etc.

conf_level

Confidence level for fixed-effect confidence intervals (default 0.95).

digits

Decimal places for numeric output (default 2).

output

Output target: "console", "word", or "latex".

file

Path for Word output when output = "word".

table_title

Optional caption for the fixed-effects table (default "Multilevel Model Results").

Details

The intraclass correlation coefficient (ICC) quantifies the proportion of total variance that lies between clusters (Level 2 units). An ICC near 0 suggests little clustering; an ICC near 1 suggests observations within clusters are nearly identical. Marginal R-squared reflects variance explained by fixed effects alone; conditional R-squared reflects variance explained by the full model (fixed + random). When MuMIn is not available, R-squared is approximated following Nakagawa and Schielzeth (2013). P-values for fixed effects use Satterthwaite degrees of freedom when lmerTest is installed, and a normal approximation otherwise.

Value

Invisibly returns a list with elements:

fixed_effects

A list (one entry per model) of data.frames containing fixed-effect estimates, standard errors, t-values, p-values (Satterthwaite via lmerTest if installed, else normal approximation), and confidence intervals.

random_effects

A list (one entry per model) of data.frames with random-effect group names, variance components, and standard deviations.

icc

A named numeric vector of intraclass correlation coefficients (ICC), one per model, computed as \sigma^2_u / (\sigma^2_u + \sigma^2_e).

r2

A data.frame with marginal R-squared (variance explained by fixed effects only) and conditional R-squared (variance explained by fixed + random effects) for each model. Computed via MuMIn if available, else a Nakagawa-Schielzeth approximation.

model_comparison

A data.frame of likelihood ratio test results if more than one model is supplied, else NULL. Columns: Model, df (number of parameters), AIC, BIC, logLik, Chi-sq, Chi-sq df, p.

note

A character string with the APA-style table note.

The function is called primarily for its side effect of printing or writing the tables.

Examples


  if (requireNamespace("lme4", quietly = TRUE)) {
    library(lme4)
    data(ECLS_demo, package = "statAPA")

    # Null model (random intercept only)
    m0 <- lmer(math ~ 1 + (1 | schid), data = ECLS_demo, REML = FALSE)

    # Add Level-1 predictor
    m1 <- lmer(math ~ SES + (1 | schid), data = ECLS_demo, REML = FALSE)

    # Random slope + cross-level interaction
    m2 <- lmer(math ~ SES * gender + (SES | schid),
               data = ECLS_demo, REML = FALSE)

    result <- apa_multilevel(m0, m1, m2,
                             model_names = c("Null", "SES", "SES x Gender"))
    str(result$icc)
    str(result$r2)
  }


APA-style estimated marginal means plot (ANOVA / ANCOVA)

Description

Plots estimated marginal means with 95% confidence intervals for a specified factor in an Analysis of Variance (ANOVA) or Analysis of Covariance (ANCOVA) model, using emmeans.

Usage

apa_plot_anova(model, by, conf_level = 0.95)

Arguments

model

Fitted lm, aov, or mixed model object that includes the factor by.

by

Character scalar: factor name for which to estimate and plot marginal means.

conf_level

Confidence level for the intervals (default 0.95).

Value

A ggplot object showing point estimates and error bars (95% confidence intervals) for each level of by, with theme_apa() applied.

Examples

fit <- aov(mpg ~ factor(cyl), data = mtcars)
apa_plot_anova(fit, by = "cyl")

APA-style regression plot with confidence interval ribbon

Description

For lm or glm models: draws a fitted line with a shaded 95% confidence interval ribbon along a focal continuous predictor. If ggeffects is available and by is supplied, plots separate interaction lines with ribbons by group.

Usage

apa_plot_regression(model, focal, by = NULL, conf_level = 0.95)

Arguments

model

Fitted lm or glm object.

focal

Character scalar: the focal continuous predictor to place on the x-axis (must appear in model.frame(model)).

by

Optional character scalar: name of a factor for separate lines (requires ggeffects).

conf_level

Confidence level for the interval ribbon (default 0.95).

Value

A ggplot object showing the fitted line and confidence interval ribbon for the focal predictor, with theme_apa() applied.

Examples

fit <- lm(mpg ~ wt + hp, data = mtcars)
apa_plot_regression(fit, focal = "wt")

APA-style residual diagnostic plots

Description

Produces either a Residuals vs Fitted plot or a Normal Q-Q plot for a fitted model, styled with theme_apa().

Usage

apa_plot_residuals(model, type = c("rvf", "qq"))

Arguments

model

Fitted lm, glm, or lmerMod object.

type

One of "rvf" (Residuals vs Fitted; default) or "qq" (Normal Q-Q plot).

Value

A ggplot object. For type = "rvf": residuals on the y-axis versus fitted values on the x-axis. For type = "qq": standardized residuals plotted against theoretical normal quantiles with a 45-degree reference line.

Examples

fit <- lm(mpg ~ wt + hp, data = mtcars)
apa_plot_residuals(fit, type = "rvf")
apa_plot_residuals(fit, type = "qq")

APA 7-style post-hoc pairwise comparisons (emmeans)

Description

Produces APA-formatted pairwise comparisons of estimated marginal means. Works with lm/glm/lmer/glmer/aov models. Requires the factor by to be in the model and have at least 2 levels. Supports multiple contrast methods (e.g., "pairwise", "revpairwise", "trt.vs.ctrl") and p-value adjust options ("tukey", "bonferroni", "holm", "sidak", etc.).

Usage

apa_posthoc(
  model,
  by,
  method = "pairwise",
  adjust = "tukey",
  conf_level = 0.95,
  output = c("console", "word", "latex"),
  file = NULL,
  table_title = "Post-hoc Pairwise Comparisons"
)

Arguments

model

Fitted model (aov/lm/glm/lmer/ glmer).

by

Character scalar: factor name to compare (must be in the model).

method

Character: contrast type for emmeans::contrast() (default "pairwise").

adjust

Character: multiplicity correction method (default "tukey").

conf_level

Numeric in (0,1): confidence level for confidence intervals (default .95).

output

"console", "word", or "latex".

file

Path for Word output (used when output = "word").

table_title

Optional caption for the table (default "Post-hoc Pairwise Comparisons").

Value

Invisibly returns a list with two elements:

pairs

A data.frame of all pairwise contrasts as returned by summary(emmeans::contrast(...)), with columns including contrast (pair label), estimate (mean difference), SE (standard error), the test statistic (t.ratio or z.ratio depending on the model), df, p.value (adjusted), and lower.CL/upper.CL (confidence interval bounds).

note

A character string with the APA-style table note describing the contrast method, adjustment, and confidence level.

When output = "latex", the list also contains a latex element with the LaTeX table string. Returns NULL invisibly if the factor has fewer than 2 levels. The function is called primarily for its side effect of printing or writing the table.

Examples

fit <- aov(mpg ~ factor(cyl), data = mtcars)
result <- apa_posthoc(fit, by = "cyl")
str(result$pairs)

APA proportion test (one- or two-sample) with optional risk difference, risk ratio, and odds ratio

Description

APA proportion test (one- or two-sample) with optional risk difference, risk ratio, and odds ratio

Usage

apa_prop_test(
  x,
  n,
  y = NULL,
  m = NULL,
  p0 = NULL,
  correct = TRUE,
  conf.level = 0.95,
  output = c("silent", "console")
)

Arguments

x

Successes (length 1 for one-sample; length 2 for two-sample).

n

Trials (length 1 for one-sample; length 2 for two-sample).

y

Deprecated: if supplied together with m, will be bound into x.

m

Deprecated: if supplied together with y, will be bound into n.

p0

Null proportion for one-sample; MUST be NULL for two-sample.

correct

Logical, continuity correction (passed to stats::prop.test).

conf.level

Confidence level for intervals (default 0.95).

output

"console" to print an APA-formatted summary to the console; "silent" returns invisibly without printing.

Value

Invisibly returns a list with two elements:

table

A data.frame with one row containing columns Test (description of the test), Estimate (sample proportion or difference), 95% CI (confidence interval string), Stat (chi-square statistic), df, p (formatted p-value), RD (risk difference with CI, two-sample only), RR (risk ratio with CI, two-sample only), and OR (odds ratio with CI, two-sample only). One-sample rows have empty strings for RD, RR, and OR.

note

A character string with the APA-style table note describing abbreviations and methods used.

Examples

# One-sample: test whether proportion equals 0.5
apa_prop_test(x = 35, n = 50, p0 = 0.5, output = "console")

# Two-sample: compare two groups
apa_prop_test(x = c(30, 20), n = c(50, 50), output = "console")

Quick residual plots (helper)

Description

Prints Residuals vs Fitted and Normal Q-Q plots using APA theme helpers.

Usage

apa_resid_plots(model)

Arguments

model

Fitted lm/glm/lmerMod.

Value

No return value; called for its side effect of printing two diagnostic plots (Residuals vs Fitted and Normal Q-Q) to the active graphics device.


APA-Style Regression Table with Robust or Clustered Standard Errors

Description

Generates an APA-formatted regression table using Heteroscedasticity-Consistent (HC) or cluster-robust standard errors via sandwich and lmtest.

Usage

apa_robust(
  model,
  type = c("HC3", "HC1", "HC0", "HC2", "HC4", "HC4m", "HC5"),
  cluster = NULL,
  output = c("console", "word", "latex"),
  file = NULL
)

Arguments

model

Fitted lm or glm object.

type

Heteroscedasticity-Consistent (HC) estimator type, one of "HC0", "HC1", "HC2", "HC3" (default), "HC4", "HC4m", "HC5". Ignored if cluster is provided.

cluster

Optional vector/factor (length = observations in the model) for one-way cluster-robust standard errors.

output

Output target: "console", "word", or "latex".

file

Path for Word output if output = "word".

Value

Invisibly returns a list with two elements:

table

A data.frame of formatted fixed-effects results with columns Predictor, b (unstandardized coefficient), SE (standard error), t (t- or z-statistic), p (formatted p-value), and 95% CI (confidence interval string based on normal approximation).

vcov

The variance-covariance matrix used (either the Heteroscedasticity-Consistent (HC) or cluster-robust matrix from sandwich).

The function is called primarily for its side effect of printing or writing the table.

Examples

fit <- lm(mpg ~ wt + hp, data = mtcars)
result <- apa_robust(fit)           # HC3 standard errors (default)
str(result$table)

result_cl <- apa_robust(fit, cluster = mtcars$cyl)  # cluster-robust
str(result_cl$table)


APA t-Test (one-sample, two-sample, or paired)

Description

Runs a t-test and returns an APA-styled result object suitable for printing in the console or conversion to a flextable via apa_to_flextable().

Usage

apa_t_test(
  x,
  y = NULL,
  mu = 0,
  paired = FALSE,
  var.equal = FALSE,
  conf.level = 0.95,
  output = c("silent", "console")
)

Arguments

x

Numeric vector of data (group 1 for two-sample; or the single sample).

y

Optional numeric vector of data (group 2 for two-sample; or paired partner for paired = TRUE).

mu

Null hypothesis mean for one-sample/paired tests. Default = 0.

paired

Logical. If TRUE, performs a paired t-test (requires x and y).

var.equal

Logical. If TRUE, assumes equal variances for two-sample test (pooled t).

conf.level

Confidence level for interval(s). Default = 0.95.

output

If "console", prints a formatted APA table to the console via message(). "silent" returns invisibly without any console output.

Value

Invisibly returns a list with two elements:

table

A data.frame with one row and columns Test (label identifying the test type), Estimate (sample mean, mean difference, or mean of differences), 95% CI (confidence interval string for the estimate), t (t-statistic), df (degrees of freedom; Welch df for unequal-variance tests), p (formatted p-value), and g (Hedges' g effect size).

note

A character string with the APA-style table note.

This list is compatible with apa_to_flextable() for export to Word or PowerPoint.

Examples

# One-sample
apa_t_test(mtcars$mpg, mu = 20, output = "console")

# Two-sample (Welch)
apa_t_test(mtcars$mpg[mtcars$am == 0], mtcars$mpg[mtcars$am == 1],
           output = "console")

# Paired
apa_t_test(sleep$extra[sleep$group == 1],
           sleep$extra[sleep$group == 2],
           paired = TRUE, output = "console")

APA 7-style regression / multilevel model table

Description

APA 7-style regression / multilevel model table

Usage

apa_table(
  model,
  output = c("console", "word", "latex"),
  file = NULL,
  conf_level = 0.95,
  digits = 2,
  cluster_id = NULL,
  show_random = TRUE,
  table_title = NULL
)

Arguments

model

Fitted model: lm, glm, lmer, or glmer.

output

"console", "word", or "latex".

file

Path for Word output (when output = "word").

conf_level

Confidence level for confidence intervals (default .95).

digits

Decimal places for numeric columns (default 2).

cluster_id

Optional cluster vector (for reporting level-2 N in multilevel models).

show_random

Logical; include random effects and intraclass correlation coefficient (ICC) if a mixed model is supplied.

table_title

Optional caption; autogenerated if NULL.

Value

Invisibly returns a list with the following elements:

fixed_effects

A data.frame of fixed-effect estimates with columns term, estimate, se, stat, p, ci_low, and ci_high.

random_effects

A list with var_between, var_within, and ICC (intraclass correlation coefficient), or NULL for non-mixed models.

sample_info

A list with N_level1 and N_level2 (number of observations and clusters, respectively).

p_method

A character string describing the method used to compute p-values.

note

A character string with the APA-style table note.

When output = "latex", the list also contains a latex element with the LaTeX table string. The function is called primarily for its side effect of printing or writing the table.

Examples

fit <- lm(mpg ~ wt + hp + factor(cyl), data = mtcars)
result <- apa_table(fit)
str(result$fixed_effects)

Convert an statAPA result into a flextable

Description

Converts the list/data-frame objects returned by functions such as 'apa_table()', 'apa_descriptives()', 'apa_anova()', and 'apa_posthoc()' into an APA-styled flextable ready for inclusion in Word/PowerPoint.

Usage

apa_to_flextable(x, note = NULL, digits = 2)

Arguments

x

Output from an 'statAPA' function (list or data.frame).

note

Optional character string printed as the table note.

digits

Numeric digits for rounding numeric columns (default 2).

Value

A flextable object styled according to APA 7e.

Examples


  res <- apa_table(lm(mpg ~ wt + cyl, data = mtcars))
  ft  <- apa_to_flextable(res)
  doc <- officer::read_docx()
  doc <- flextable::body_add_flextable(doc, ft)
  print(doc, target = tempfile(fileext = ".docx"))


APA 7-style two-way ANOVA table with interaction and simple effects

Description

Fits a two-way factorial Analysis of Variance (ANOVA) and produces an APA-formatted omnibus table (main effects + interaction) with effect sizes. Optionally computes simple effects of factorA at each level of factorB (or vice versa) via emmeans.

Usage

apa_twoway_anova(
  formula,
  data,
  factorA,
  factorB,
  type = c("II", "III"),
  es = c("partial_eta2", "eta2", "omega2"),
  simple_effects = TRUE,
  conf_level = 0.95,
  output = c("console", "word", "latex"),
  file = NULL,
  table_title = "Two-Way ANOVA Results"
)

Arguments

formula

A model formula of the form y ~ A * B or y ~ A + B + A:B. Both main effects and the interaction must be present.

data

A data frame containing the variables.

factorA

Character: name of the first factor in data.

factorB

Character: name of the second factor in data.

type

Sums-of-squares type: "II" (default) or "III".

es

Effect size to report: "partial_eta2" (default), "eta2", or "omega2".

simple_effects

Logical. If TRUE (default), compute and print simple effects of factorA at each level of factorB.

conf_level

Confidence level for estimated marginal means (default 0.95).

output

Output target: "console", "word", or "latex".

file

Path for Word output when output = "word".

table_title

Optional caption for the omnibus table (default "Two-Way ANOVA Results").

Details

A two-way factorial Analysis of Variance (ANOVA) tests main effects of two factors and their interaction on a continuous outcome. When the interaction is significant it is typically more informative to inspect simple effects (the effect of one factor at each level of the other) rather than main effects alone. Simple effects are computed as one-way Analysis of Variance (ANOVA) F-tests using emmeans::joint_tests() applied within each level of factorB.

Value

Invisibly returns a list with elements:

model

The fitted lm object.

anova_table

A data.frame of the omnibus two-way Analysis of Variance (ANOVA) results with columns Source (effect name), SS (Sum of Squares), df, MS (Mean Square), F, p (formatted p-value), and the chosen effect-size column (eta2, partial_eta2, or omega2).

simple_effects

A data.frame of simple-effects tests of factorA within each level of factorB, or NULL if simple_effects = FALSE or computation failed. Columns match anova_table.

marginal_means

A data.frame of estimated marginal means for all combinations of factorA and factorB, from emmeans::emmeans().

note

A character string with the APA-style table note.

The function is called primarily for its side effect of printing or writing the tables.

Examples

mtcars2 <- mtcars
mtcars2$cyl  <- factor(mtcars2$cyl)
mtcars2$gear <- factor(mtcars2$gear)
result <- apa_twoway_anova(
  mpg ~ cyl * gear,
  data    = mtcars2,
  factorA = "cyl",
  factorB = "gear"
)
str(result$anova_table)

APA z-test for mean(s) with known population standard deviation(s)

Description

APA z-test for mean(s) with known population standard deviation(s)

Usage

apa_z_test_mean(
  x,
  y = NULL,
  sigma_x,
  sigma_y = NULL,
  mu = 0,
  alternative = c("two.sided", "less", "greater"),
  conf.level = 0.95,
  output = c("console", "list")
)

Arguments

x

Numeric vector (or sample 1 for a two-sample test).

y

Optional numeric vector for a two-sample z-test (independent samples).

sigma_x

Known population standard deviation for x.

sigma_y

Known population standard deviation for y (two-sample only).

mu

Null mean (one-sample) or null mean difference (two-sample); default 0.

alternative

"two.sided", "less", or "greater".

conf.level

Confidence level (default .95).

output

"console" prints an APA-formatted summary to the console via message(); "list" returns the result invisibly without printing.

Value

A list with two elements:

table

A data.frame with one row containing columns Test (description of the test), Estimate (sample mean or mean difference), 95% CI (confidence interval string for the mean or mean difference), stat (z-statistic), df (NA for z-tests, which have no finite degrees of freedom), p (formatted p-value), and d (Cohen's d with 95% confidence interval, computed using the known population standard deviation(s) as a reporting convenience).

note

A character string with the APA-style table note.

Examples

# One-sample z-test
apa_z_test_mean(mtcars$mpg, sigma_x = 6, mu = 20, output = "console")

# Two-sample z-test
x1 <- mtcars$mpg[mtcars$am == 0]
x2 <- mtcars$mpg[mtcars$am == 1]
apa_z_test_mean(x1, y = x2, sigma_x = 6, sigma_y = 6, output = "console")

Save a ggplot figure with APA-friendly defaults

Description

A thin wrapper around ggplot2::ggsave() that applies dimensions and resolution appropriate for American Psychological Association (APA) journal submissions (6.5 in wide, 4.5 in tall, 300 dpi, white background).

Usage

save_apa(filename, plot, width = 6.5, height = 4.5, dpi = 300)

apa_plot_descriptives(data, y, group, show_points = FALSE)

Arguments

filename

Path to the output file. The file extension determines the format (e.g., ".png", ".pdf", ".tiff").

plot

A ggplot object to save.

width

Width in inches (default 6.5).

height

Height in inches (default 4.5).

dpi

Resolution in dots per inch (default 300).

data

A data frame (apa_plot_descriptives only).

y

Character: name of the numeric outcome variable (apa_plot_descriptives only).

group

Character: name of the grouping factor (apa_plot_descriptives only).

show_points

Logical; overlay jittered points, default FALSE (apa_plot_descriptives only).

Value

No return value; called for its side effect of writing the plot to disk via ggplot2::ggsave().

Examples

library(ggplot2)
p   <- ggplot(mtcars, aes(wt, mpg)) + geom_point()
tmp <- tempfile(fileext = ".png")
save_apa(tmp, p)
file.remove(tmp)

Set global defaults for statAPA table styling

Description

Controls the default visual style applied to flextable output produced by apa_to_flextable() and related functions throughout the session.

Usage

set_apa_style(
  style = c("auto", "decked", "plain", "none"),
  note_default = TRUE
)

Arguments

style

Character, one of "auto", "decked", "plain", or "none". "auto" (default) detects whether column names follow a <group>_<stat> pattern and adds a spanner header automatically. "decked" forces spanner headers. "plain" suppresses spanners. "none" removes all borders.

note_default

Logical; if TRUE (default) a generic APA note is appended when the calling function has not supplied one.

Value

Invisibly returns the previous option values (a named list), making the function suitable for use with on.exit() to restore settings. Called primarily for its side effect of setting options().

Examples

old <- set_apa_style(style = "plain", note_default = FALSE)
# restore when done
options(old)

APA-style ggplot2 theme

Description

A clean, minimal theme suitable for American Psychological Association (APA) style figures: no panel gridlines, bold axis titles, and a centered bold plot title.

Usage

theme_apa(base_size = 12)

Arguments

base_size

Base font size in points (default 12).

Value

A theme object from ggplot2 that can be added to any ggplot with + theme_apa(). Applies no panel gridlines, bold axis titles, black axis text, and a centered bold plot title consistent with American Psychological Association (APA) figure guidelines.

Examples

library(ggplot2)
ggplot(mtcars, aes(wt, mpg)) +
  geom_point() +
  theme_apa()