| Title: | APA 7th Edition Statistical Tables, Plots, and Multilevel Model Reports |
|---|---|
| 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). |
| Authors: | Subir Hait [aut, cre] (ORCID: <https://orcid.org/0009-0004-9871-9677>) |
| Maintainer: | Subir Hait <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.1.0 |
| Built: | 2026-05-17 07:51:19 UTC |
| Source: | https://github.com/causalfragility-lab/statapa |
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).
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" )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" )
formula |
A model formula, e.g. |
data |
A data frame containing the variables in |
covariate |
Character vector naming the covariate column(s) in
|
focal |
Character scalar: the name of the focal (grouping) factor whose adjusted means will be reported. |
type |
Sums-of-squares type: |
es |
Effect size to report: |
conf_level |
Confidence level for adjusted-means intervals (default
|
output |
Output target: |
file |
Path for Word output when |
table_title |
Optional caption for the omnibus table (default
|
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.
Invisibly returns a list with elements:
modelThe fitted lm object.
anova_tableA 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_meansA data.frame of covariate-adjusted
marginal means for focal, from emmeans::emmeans(), with
columns focal, Adjusted M (adjusted mean),
SE, and 95% CI.
noteA character string with the APA-style table note.
The function is called primarily for its side effect of printing or writing the tables.
# 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)# 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
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" )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" )
model |
An |
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 |
table_title |
Optional caption title (default "ANOVA Results"). |
Invisibly returns a list with two components:
anovaThe full ANOVA table as returned by
car::Anova(), including all rows.
tableA 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.
fit <- lm(mpg ~ factor(cyl) + wt, data = mtcars) result <- apa_anova(fit) str(result$table)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
apa_chisq( x, p = NULL, correct = FALSE, simulate.p.value = FALSE, B = 2000, output = c("console", "list") )apa_chisq( x, p = NULL, correct = FALSE, simulate.p.value = FALSE, B = 2000, output = c("console", "list") )
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 |
A list with two elements:
tableA 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).
noteA character string with the APA-style table note.
# 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))# 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
apa_descriptives( data, vars, group = NULL, digits = 2, output = c("console", "word", "latex"), file = NULL, table_title = NULL )apa_descriptives( data, vars, group = NULL, digits = 2, output = c("console", "word", "latex"), file = NULL, table_title = NULL )
data |
Data frame. |
vars |
Character vector of variable names to summarize. |
group |
Optional single grouping variable name in |
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". |
Invisibly returns a list with two elements:
descriptives_dfA 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.
noteA 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.
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)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)
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.
apa_hetero(model, output = c("console", "word", "latex"), file = NULL)apa_hetero(model, output = c("console", "word", "latex"), file = NULL)
model |
Fitted |
output |
Output target: one of |
file |
Path for Word output if |
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.
Invisibly returns a data.frame of test results with columns:
TestName of the test run (e.g., "Breusch-Pagan",
"Non-Constant Variance (NCV)").
StatThe test statistic (formatted to 2 decimal places).
dfDegrees of freedom for the test statistic.
pFormatted 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.
fit <- lm(mpg ~ wt + hp, data = mtcars) result <- apa_hetero(fit) str(result)fit <- lm(mpg ~ wt + hp, data = mtcars) result <- apa_hetero(fit) str(result)
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.
apa_homoskedasticity( model, group = NULL, center = c("mean", "median"), alpha = 0.05, output = c("console", "word", "latex"), file = NULL )apa_homoskedasticity( model, group = NULL, center = c("mean", "median"), alpha = 0.05, output = c("console", "word", "latex"), file = NULL )
model |
Fitted |
group |
Optional grouping factor (for Levene/Brown-Forsythe). If
provided, |
center |
Character for Levene center, one of |
alpha |
Significance level for the textual conclusion (default 0.05). |
output |
"console", "word", or "latex". |
file |
Path for Word output when |
Invisibly returns a data.frame of test results with columns:
TestName of the test run (e.g.,
"Breusch-Pagan", "White (BP with fitted + fitted^2)",
"Levene (mean)", or "Brown-Forsythe (Levene, median)").
StatThe numeric test statistic.
dfDegrees of freedom (may be NA for some tests).
pThe 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.
fit <- lm(mpg ~ wt + cyl, data = mtcars) result <- apa_homoskedasticity(fit, output = "console") str(result)fit <- lm(mpg ~ wt + cyl, data = mtcars) result <- apa_homoskedasticity(fit, output = "console") str(result)
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.
apa_manova( formula, data, type = c("II", "III"), output = c("console", "word", "latex"), file = NULL, table_title = "MANOVA Results" )apa_manova( formula, data, type = c("II", "III"), output = c("console", "word", "latex"), file = NULL, table_title = "MANOVA Results" )
formula |
A formula of the form |
data |
A data frame containing the variables in |
type |
Sums-of-squares type passed to |
output |
Output target: |
file |
Path for Word output when |
table_title |
Optional caption (default |
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.
Invisibly returns a list with elements:
manovaThe raw manova model object.
summaryThe summary list from summary.manova(),
containing one element per test statistic ("Pillai",
"Wilks", "Hotelling-Lawley", "Roy").
tableA 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).
noteA character string with the APA-style table note.
The function is called primarily for its side effect of printing or writing the table.
# One-way MANOVA: sepal and petal length by species result <- apa_manova( cbind(Sepal.Length, Petal.Length) ~ Species, data = iris ) str(result$table)# One-way MANOVA: sepal and petal length by species result <- apa_manova( cbind(Sepal.Length, Petal.Length) ~ Species, data = iris ) str(result$table)
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.
apa_multilevel( ..., model_names = NULL, conf_level = 0.95, digits = 2, output = c("console", "word", "latex"), file = NULL, table_title = "Multilevel Model Results" )apa_multilevel( ..., model_names = NULL, conf_level = 0.95, digits = 2, output = c("console", "word", "latex"), file = NULL, table_title = "Multilevel Model Results" )
... |
One or more fitted |
model_names |
Optional character vector of labels for the models (same
length as |
conf_level |
Confidence level for fixed-effect confidence intervals
(default |
digits |
Decimal places for numeric output (default |
output |
Output target: |
file |
Path for Word output when |
table_title |
Optional caption for the fixed-effects table (default
|
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.
Invisibly returns a list with elements:
fixed_effectsA 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_effectsA list (one entry per model) of
data.frames with random-effect group names, variance components,
and standard deviations.
iccA named numeric vector of intraclass correlation
coefficients (ICC), one per model, computed as
.
r2A 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_comparisonA 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.
noteA character string with the APA-style table note.
The function is called primarily for its side effect of printing or writing the tables.
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) }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) }
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.
apa_plot_anova(model, by, conf_level = 0.95)apa_plot_anova(model, by, conf_level = 0.95)
model |
Fitted |
by |
Character scalar: factor name for which to estimate and plot marginal means. |
conf_level |
Confidence level for the intervals (default 0.95). |
A ggplot object showing point estimates and error bars
(95% confidence intervals) for each level of by, with
theme_apa() applied.
fit <- aov(mpg ~ factor(cyl), data = mtcars) apa_plot_anova(fit, by = "cyl")fit <- aov(mpg ~ factor(cyl), data = mtcars) apa_plot_anova(fit, by = "cyl")
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.
apa_plot_regression(model, focal, by = NULL, conf_level = 0.95)apa_plot_regression(model, focal, by = NULL, conf_level = 0.95)
model |
Fitted |
focal |
Character scalar: the focal continuous predictor to place on
the x-axis (must appear in |
by |
Optional character scalar: name of a factor for separate lines (requires ggeffects). |
conf_level |
Confidence level for the interval ribbon (default 0.95). |
A ggplot object showing the fitted line and confidence
interval ribbon for the focal predictor, with theme_apa() applied.
fit <- lm(mpg ~ wt + hp, data = mtcars) apa_plot_regression(fit, focal = "wt")fit <- lm(mpg ~ wt + hp, data = mtcars) apa_plot_regression(fit, focal = "wt")
Produces either a Residuals vs Fitted plot or a Normal Q-Q plot for a
fitted model, styled with theme_apa().
apa_plot_residuals(model, type = c("rvf", "qq"))apa_plot_residuals(model, type = c("rvf", "qq"))
model |
Fitted |
type |
One of |
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.
fit <- lm(mpg ~ wt + hp, data = mtcars) apa_plot_residuals(fit, type = "rvf") apa_plot_residuals(fit, type = "qq")fit <- lm(mpg ~ wt + hp, data = mtcars) apa_plot_residuals(fit, type = "rvf") apa_plot_residuals(fit, type = "qq")
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.).
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" )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" )
model |
Fitted model ( |
by |
Character scalar: factor name to compare (must be in the model). |
method |
Character: contrast type for |
adjust |
Character: multiplicity correction method (default
|
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 |
table_title |
Optional caption for the table (default "Post-hoc Pairwise Comparisons"). |
Invisibly returns a list with two elements:
pairsA 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).
noteA 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.
fit <- aov(mpg ~ factor(cyl), data = mtcars) result <- apa_posthoc(fit, by = "cyl") str(result$pairs)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
apa_prop_test( x, n, y = NULL, m = NULL, p0 = NULL, correct = TRUE, conf.level = 0.95, output = c("silent", "console") )apa_prop_test( x, n, y = NULL, m = NULL, p0 = NULL, correct = TRUE, conf.level = 0.95, output = c("silent", "console") )
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 |
Deprecated: if supplied together with |
p0 |
Null proportion for one-sample; MUST be |
correct |
Logical, continuity correction (passed to
|
conf.level |
Confidence level for intervals (default |
output |
|
Invisibly returns a list with two elements:
tableA 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.
noteA character string with the APA-style table note describing abbreviations and methods used.
# 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")# 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")
Prints Residuals vs Fitted and Normal Q-Q plots using APA theme helpers.
apa_resid_plots(model)apa_resid_plots(model)
model |
Fitted |
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.
Generates an APA-formatted regression table using Heteroscedasticity-Consistent (HC) or cluster-robust standard errors via sandwich and lmtest.
apa_robust( model, type = c("HC3", "HC1", "HC0", "HC2", "HC4", "HC4m", "HC5"), cluster = NULL, output = c("console", "word", "latex"), file = NULL )apa_robust( model, type = c("HC3", "HC1", "HC0", "HC2", "HC4", "HC4m", "HC5"), cluster = NULL, output = c("console", "word", "latex"), file = NULL )
model |
Fitted |
type |
Heteroscedasticity-Consistent (HC) estimator type, one of
|
cluster |
Optional vector/factor (length = observations in the model) for one-way cluster-robust standard errors. |
output |
Output target: |
file |
Path for Word output if |
Invisibly returns a list with two elements:
tableA 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).
vcovThe 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.
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)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)
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().
apa_t_test( x, y = NULL, mu = 0, paired = FALSE, var.equal = FALSE, conf.level = 0.95, output = c("silent", "console") )apa_t_test( x, y = NULL, mu = 0, paired = FALSE, var.equal = FALSE, conf.level = 0.95, output = c("silent", "console") )
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 |
mu |
Null hypothesis mean for one-sample/paired tests. Default = 0. |
paired |
Logical. If |
var.equal |
Logical. If |
conf.level |
Confidence level for interval(s). Default = 0.95. |
output |
If |
Invisibly returns a list with two elements:
tableA 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).
noteA character string with the APA-style table note.
This list is compatible with apa_to_flextable() for export to Word
or PowerPoint.
# 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")# 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
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 )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 )
model |
Fitted model: |
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 |
Invisibly returns a list with the following elements:
fixed_effectsA data.frame of fixed-effect
estimates with columns term, estimate, se,
stat, p, ci_low, and ci_high.
random_effectsA list with var_between,
var_within, and ICC (intraclass correlation
coefficient), or NULL for non-mixed models.
sample_infoA list with N_level1 and
N_level2 (number of observations and clusters, respectively).
p_methodA character string describing the method used to compute p-values.
noteA 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.
fit <- lm(mpg ~ wt + hp + factor(cyl), data = mtcars) result <- apa_table(fit) str(result$fixed_effects)fit <- lm(mpg ~ wt + hp + factor(cyl), data = mtcars) result <- apa_table(fit) str(result$fixed_effects)
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.
apa_to_flextable(x, note = NULL, digits = 2)apa_to_flextable(x, note = NULL, digits = 2)
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). |
A flextable object styled according to APA 7e.
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"))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"))
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.
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" )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" )
formula |
A model formula of the form |
data |
A data frame containing the variables. |
factorA |
Character: name of the first factor in |
factorB |
Character: name of the second factor in |
type |
Sums-of-squares type: |
es |
Effect size to report: |
simple_effects |
Logical. If |
conf_level |
Confidence level for estimated marginal means (default
|
output |
Output target: |
file |
Path for Word output when |
table_title |
Optional caption for the omnibus table (default
|
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.
Invisibly returns a list with elements:
modelThe fitted lm object.
anova_tableA 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_effectsA 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_meansA data.frame of estimated marginal
means for all combinations of factorA and factorB, from
emmeans::emmeans().
noteA character string with the APA-style table note.
The function is called primarily for its side effect of printing or writing the tables.
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)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)
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") )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") )
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 |
sigma_y |
Known population standard deviation for |
mu |
Null mean (one-sample) or null mean difference (two-sample); default 0. |
alternative |
|
conf.level |
Confidence level (default .95). |
output |
|
A list with two elements:
tableA 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).
noteA character string with the APA-style table note.
# 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")# 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")
A small, simulated, school-clustered dataset used in package examples and the vignette.
data(ECLS_demo)data(ECLS_demo)
A data frame with 800 rows and 4 variables:
School ID (integer, 1-20)
Standardized socioeconomic status (numeric)
Factor with levels Female, Male
Continuous math score (approx. mean 500, SD 14)
data(ECLS_demo) str(ECLS_demo)data(ECLS_demo) str(ECLS_demo)
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).
save_apa(filename, plot, width = 6.5, height = 4.5, dpi = 300) apa_plot_descriptives(data, y, group, show_points = FALSE)save_apa(filename, plot, width = 6.5, height = 4.5, dpi = 300) apa_plot_descriptives(data, y, group, show_points = FALSE)
filename |
Path to the output file. The file extension determines the
format (e.g., |
plot |
A |
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 ( |
y |
Character: name of the numeric outcome variable ( |
group |
Character: name of the grouping factor ( |
show_points |
Logical; overlay jittered points, default |
No return value; called for its side effect of writing the plot to
disk via ggplot2::ggsave().
library(ggplot2) p <- ggplot(mtcars, aes(wt, mpg)) + geom_point() tmp <- tempfile(fileext = ".png") save_apa(tmp, p) file.remove(tmp)library(ggplot2) p <- ggplot(mtcars, aes(wt, mpg)) + geom_point() tmp <- tempfile(fileext = ".png") save_apa(tmp, p) file.remove(tmp)
Controls the default visual style applied to flextable output produced by
apa_to_flextable() and related functions throughout the session.
set_apa_style( style = c("auto", "decked", "plain", "none"), note_default = TRUE )set_apa_style( style = c("auto", "decked", "plain", "none"), note_default = TRUE )
style |
Character, one of |
note_default |
Logical; if |
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().
old <- set_apa_style(style = "plain", note_default = FALSE) # restore when done options(old)old <- set_apa_style(style = "plain", note_default = FALSE) # restore when done options(old)
A clean, minimal theme suitable for American Psychological Association (APA) style figures: no panel gridlines, bold axis titles, and a centered bold plot title.
theme_apa(base_size = 12)theme_apa(base_size = 12)
base_size |
Base font size in points (default 12). |
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.
library(ggplot2) ggplot(mtcars, aes(wt, mpg)) + geom_point() + theme_apa()library(ggplot2) ggplot(mtcars, aes(wt, mpg)) + geom_point() + theme_apa()