| 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 |
| 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
\approx14)
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. |
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
|
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:
modelThe fitted
lmobject.anova_tableA
data.frameof the omnibus Analysis of Covariance (ANCOVA) results with columnsSource,SS(Sum of Squares),df,MS(Mean Square),F,p, and the chosen effect-size column.adjusted_meansA
data.frameof covariate-adjusted marginal means forfocal, fromemmeans::emmeans(), with columnsfocal,Adjusted M(adjusted mean),SE, and95% 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.
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 |
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"). |
Value
Invisibly returns a list with two components:
anovaThe full ANOVA table as returned by
car::Anova(), including all rows.tableA
data.frameformatted for APA output, with columnsSource,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, oromega2).
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 |
Value
A list with two elements:
tableA
data.framewith one row containing columnsTest(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), andValue(the numeric effect-size estimate).noteA 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 |
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_dfA
data.framewith one row per variable. Without grouping, columns areVariable,M(mean),SD(standard deviation), andN(number of non-missing observations). With grouping, there is oneM (SD)column per group level plus aTotal: M (SD)column andN.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.
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 |
output |
Output target: one of |
file |
Path for Word output if |
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:
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.
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 |
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 |
Value
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
NAfor 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.
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 |
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 |
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:
manovaThe raw
manovamodel object.summaryThe summary list from
summary.manova(), containing one element per test statistic ("Pillai","Wilks","Hotelling-Lawley","Roy").tableA
data.frameformatted for APA output with columnsEffect(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), andeta2(eta-squared, computed as1 - Wilksfor 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.
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 |
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
|
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_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
\sigma^2_u / (\sigma^2_u + \sigma^2_e).r2A
data.framewith 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.frameof likelihood ratio test results if more than one model is supplied, elseNULL. 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.
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 |
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 |
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). |
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 |
type |
One of |
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 ( |
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"). |
Value
Invisibly returns a list with two elements:
pairsA
data.frameof all pairwise contrasts as returned bysummary(emmeans::contrast(...)), with columns includingcontrast(pair label),estimate(mean difference),SE(standard error), the test statistic (t.ratioorz.ratiodepending on the model),df,p.value(adjusted), andlower.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.
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 |
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 |
|
Value
Invisibly returns a list with two elements:
tableA
data.framewith one row containing columnsTest(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), andOR(odds ratio with CI, two-sample only). One-sample rows have empty strings forRD,RR, andOR.noteA 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 |
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 |
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 |
Value
Invisibly returns a list with two elements:
tableA
data.frameof formatted fixed-effects results with columnsPredictor,b(unstandardized coefficient),SE(standard error),t(t- or z-statistic),p(formatted p-value), and95% 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.
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 |
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 |
Value
Invisibly returns a list with two elements:
tableA
data.framewith one row and columnsTest(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), andg(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.
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: |
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 |
Value
Invisibly returns a list with the following elements:
fixed_effectsA
data.frameof fixed-effect estimates with columnsterm,estimate,se,stat,p,ci_low, andci_high.random_effectsA list with
var_between,var_within, andICC(intraclass correlation coefficient), orNULLfor non-mixed models.sample_infoA list with
N_level1andN_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.
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 |
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
|
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:
modelThe fitted
lmobject.anova_tableA
data.frameof the omnibus two-way Analysis of Variance (ANOVA) results with columnsSource(effect name),SS(Sum of Squares),df,MS(Mean Square),F,p(formatted p-value), and the chosen effect-size column (eta2,partial_eta2, oromega2).simple_effectsA
data.frameof simple-effects tests offactorAwithin each level offactorB, orNULLifsimple_effects = FALSEor computation failed. Columns matchanova_table.marginal_meansA
data.frameof estimated marginal means for all combinations offactorAandfactorB, fromemmeans::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.
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 |
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 |
|
Value
A list with two elements:
tableA
data.framewith one row containing columnsTest(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(NAfor z-tests, which have no finite degrees of freedom),p(formatted p-value), andd(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.
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., |
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 |
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 |
note_default |
Logical; if |
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()