| Title: | Writing Documents in American Psychological Association Style, Seventh Edition |
| Version: | 0.3.0 |
| Description: | Create tables and format statistics in the style of the Publication Manual of the American Psychological Association, Seventh Edition. Functions turn fitted models and data into APA-style tables (regression, mixed, multinomial, count, and generalized additive models; ANOVA; hypothesis tests; descriptive statistics; correlations; reliability; factor analysis; structural equation models; estimated marginal means; and meta-analyses), write their table notes, and extend 'flextable' for tables made by hand. |
| License: | CC0 |
| URL: | https://github.com/wjschne/apa7, https://wjschne.github.io/apa7/ |
| BugReports: | https://github.com/wjschne/apa7/issues |
| Depends: | R (≥ 4.1.0) |
| Imports: | cli, correlation, dplyr, effectsize, flextable, ftExtra, glue, insight, knitr, parameters, performance, psych, purrr, rlang, S7, scales, shiny, signs, snakecase, stringr, systemfonts, tibble, tidyr, tidyselect (≥ 1.2.0) |
| Suggests: | afex, betareg, bsicons, bslib, car, carData, conflicted, forcats, fresh, geepack, ggbeeswarm, ggplot2, glmmTMB, jsonlite, lavaan, lme4, lmerTest, marginaleffects, MASS, metadat, metafor, mgcv, modelbased, nFactors, nlme, nnet, ordinal, pbkrtest, pscl, quantreg, quarto, ragg, robustbase, rclipboard, readr, rmarkdown, sandwich, shinyWidgets, spelling, survival, svglite, testthat (≥ 3.0.0), tippy, toastui, withr, yaml |
| VignetteBuilder: | knitr, quarto |
| Config/Needs/website: | AER, curl, gfonts, psychTools, quarto, viridis, wjschne/ggdiagram |
| Config/testthat/edition: | 3 |
| Encoding: | UTF-8 |
| Language: | en-US |
| Config/roxygen2/version: | 8.1.1 |
| NeedsCompilation: | no |
| Packaged: | 2026-12-01 11:16:42 UTC; renee |
| Author: | W. Joel Schneider |
| Maintainer: | W. Joel Schneider <w.joel.schneider@gmail.com> |
| Repository: | CRAN |
| Date/Publication: | 2026-12-01 11:50:02 UTC |
apa7: Writing Documents in American Psychological Association Style, Seventh Edition
Description
Create tables and format statistics in the style of the Publication Manual of the American Psychological Association, Seventh Edition. Functions turn fitted models and data into APA-style tables (regression, mixed, multinomial, count, and generalized additive models; ANOVA; hypothesis tests; descriptive statistics; correlations; reliability; factor analysis; structural equation models; estimated marginal means; and meta-analyses), write their table notes, and extend 'flextable' for tables made by hand.
Author(s)
Maintainer: W. Joel Schneider w.joel.schneider@gmail.com (ORCID) [copyright holder]
Authors:
W. Joel Schneider w.joel.schneider@gmail.com (ORCID) [copyright holder]
See Also
Useful links:
Report bugs at https://github.com/wjschne/apa7/issues
Add break columns
Description
Inserts an empty column after (or before) each selected column. In
apa_flextable(), empty columns separate groups of columns, such as
those under different column spanners.
Usage
add_break_columns(
data,
...,
.before = FALSE,
omit_first = FALSE,
omit_last = FALSE,
d
)
Arguments
data |
data.frame or tibble |
... |
columns after which break columns are inserted: unquoted or
quoted names, or tidyselect helpers (e.g., |
.before |
if |
omit_first |
if |
omit_last |
if |
d |
deprecated; use |
Value
data.frame or tibble
Examples
d <- data.frame(x_n = 3, x_mean = 4,
y_n = 5, y_mean = 6,
z_n = 4, z_mean = 4)
# Unquoted variable names
add_break_columns(d, x_mean)
# Character vector
add_break_columns(d, c("y_n", "z_n"), .before = TRUE)
# Tidyselect function (contains, starts_with, ends_with,
# matches, num_range, all_of, any_of)
# Insert columns after all columns
# ending with "_mean" except the last instance
add_break_columns(d,
dplyr::ends_with("_mean"),
omit_last = TRUE)
Make a column into a list column
Description
Make a column into a list column
Usage
add_list_column(
data,
...,
type = c("1", "a", "A", "I", "i"),
sep = ". ",
merge = FALSE
)
Arguments
data |
data.frame or tibble |
... |
Column name or tidyselect function. Select columns. Default is first column |
type |
list type: |
sep |
text between the list label and the item (default: |
merge |
If |
Value
data.frame
Examples
d <- data.frame(x = letters[1:5], y = letters[2:6])
# default is first column
add_list_column(d) |>
apa_flextable()
# select any column
add_list_column(d, y) |>
apa_flextable()
add_list_column(d, type = "a", sep = ") ") |>
apa_flextable()
add_list_column(d, merge = TRUE)
Adds stars next to a column based on p-values
Description
Adds stars next to a column based on p-values
Usage
add_star_column(
data,
...,
p = "p",
merge = FALSE,
superscript = TRUE,
star = "\\*",
alpha = c(0.05, 0.01, 0.001),
first_alpha_marginal = FALSE,
add_trailing_space = FALSE,
prefix = "\\"
)
Arguments
data |
data.frame or tibble |
... |
Column name or tidyselect function. Select columns |
p |
Column name or tidyselect function. Select p-value column name |
merge |
merge and balance columns (default: |
superscript |
make as superscript |
star |
text for making stars |
alpha |
vector of thresholds |
first_alpha_marginal |
if TRUE, the first alpha value is treated as marginal and gets a dagger instead of a star |
add_trailing_space |
if TRUE, adds a trailing space after the stars (default: FALSE) |
prefix |
usually backslashes to prevent markdown from interpreting asterisks as bullets or italics |
Value
data.frame
Examples
data.frame(b = c(1.4,2.2),
p = c(.54, .02)) |>
add_star_column(b, p)
Align text on center text (default is decimal)
Description
align_chr() formats numbers and pads them on both sides of the decimal
point (or another center character) so that every value has the same
width. When the column is centered, the decimal points line up.
Usage
align_chr(
x,
accuracy = NULL,
trim_leading_zeros = FALSE,
drop0trailing = FALSE,
add_plusses = FALSE,
padding_character = NULL,
center = ".",
format_integers = FALSE,
side = c("both", "left", "right"),
NA_value = "",
format_numeric_character = FALSE,
...
)
Arguments
x |
vector (numeric or character) |
accuracy |
number to round to. If NULL, the current default accuracy set with |
trim_leading_zeros |
if |
drop0trailing |
Drop trailing zeros |
add_plusses |
if |
padding_character |
character to use for padding, default is |
center |
text on which to align text. Center on decimal by default, but can be any text. |
format_integers |
If TRUE, integers will be formatted with digits |
side |
side on which to make text of equal width |
NA_value |
value to replace NA |
format_numeric_character |
format character variables with numeric content |
... |
additional arguments passed to |
Details
With a few minor details omitted, align_chr() does roughly this:
If
format_numeric_character = TRUE, converts text made only of digits, minus signs, and periods to numbers.Formats numbers with
signs::signs(): rounds them toaccuracy, replaces hyphens with true minus signs, and adds commas to large numbers. Plus signs are added ifadd_plusses = TRUE, leading zeros are removed iftrim_leading_zeros = TRUE, and trailing zeros are dropped ifdrop0trailing = TRUE. Whole numbers are not given decimals unlessformat_integers = TRUE.Splits each value at the first
centercharacter, then pads the part before it on the left and the part after it on the right (sidelimits the padding to one side), so that every value has the same width on each side of the center.
By default, values are padded with figure spaces, which are as wide as a
digit. With this default, if width_aware_padding = TRUE in
apa7_defaults() (the default) and the default font is installed, values
are instead padded to the same rendered width in that font (see
num_pad()), so that values with minus signs, commas, or markdown still
line up. Other padding_character values are counted in characters.
The padded values line up only if every cell in the column is aligned the
same way. apa_flextable() centers the columns of numbers and lines up
padded values (see its Details).
Value
character vector
Examples
align_chr(c(1, 10, 100))
Set defaults for apa7 package
Description
Sets options that apply to all apa7 tables. Settings that are not given are left as they are.
Usage
apa7_defaults(
accuracy = NULL,
font_family = NULL,
font_size = NULL,
line_spacing = NULL,
intercept_text = NULL,
column_formats = NULL,
number_formatter = NULL,
trim_leading_zero = NULL,
width_aware_padding = NULL,
page_width = NULL,
landscape_width = NULL,
column_width = NULL,
table_width = NULL,
print = NULL,
citations = NULL,
reset = FALSE
)
Arguments
accuracy |
rounding accuracy of numbers in tables (default: .01, for
two decimals). Model tables such as |
font_family |
font family |
font_size |
font size of tables and their notes, in points (default: 12) |
line_spacing |
spacing between the lines of tables' headers and bodies: 2 (default) for double spacing, 1.5, or 1 for single spacing. APA style allows any of these in tables. Table notes are always single-spaced. |
intercept_text |
label of the intercept row in regression tables (default: |
column_formats |
a |
number_formatter |
function that formats numbers that can exceed 1 in absolute value (e.g., coefficients, standard errors, and test statistics). It takes a numeric vector and |
trim_leading_zero |
function that formats numbers that cannot exceed 1 in absolute value (e.g., correlations, standardized coefficients, and R^2^), which APA style writes without a leading zero. By default, |
width_aware_padding |
if |
page_width |
width of the text area of a portrait page, which tables
fill with |
landscape_width |
width of the text area of a landscape page, in
inches, which tables fill with |
column_width |
width of one column of a two-column page, in inches,
which tables fill with |
table_width |
default width of tables, in any of the forms that the
|
print |
how tables made by apa7 functions (see apa7_tbl) are
displayed: |
citations |
how articles cited in table notes are written: |
reset |
if |
Details
Each setting except column_formats, number_formatter, and
trim_leading_zero is stored as an R option (e.g.,
apa7_defaults(page_width = "a4") sets options(apa7.page_width = "a4")),
so it can also be set with options(), including in an .Rprofile file
that runs at the start of every R session, before apa7 is loaded:
| Argument | Option | Default |
accuracy | apa7.accuracy | .01 |
font_family | apa7.font_family | "Times New Roman" |
font_size | apa7.font_size | 12 |
line_spacing | apa7.line_spacing | 2 |
intercept_text | apa7.intercept_text | "Constant" |
width_aware_padding | apa7.width_aware_padding | TRUE |
page_width | apa7.page_width | 6.5 |
landscape_width | apa7.landscape_width | NA (from page_width) |
column_width | apa7.column_width | NA (from page_width) |
table_width | apa7.table_width | 1 |
print | apa7.print | "auto" |
citations | apa7.citations | "auto"
|
column_formats, number_formatter, and trim_leading_zero are objects
that need apa7 to be loaded, so they are set only with apa7_defaults()
and last for the R session.
When page_width and table_width are not set, a Quarto or R Markdown
document being rendered supplies them: its papersize sets the paper, and
apaquarto's documentmode sets the margins (0.75 inches on each side in
journal mode, jou, and 1.5 inches on the left in thesis mode). In
journal mode, which sets the text in two columns, tables are as wide as a
column by default. A setting made with apa7_defaults() or options()
overrides the document.
The default column formats follow accuracy: changing it (with
apa7_defaults() or the apa7.accuracy option) changes the number of
decimals in tables. Setting column_formats without accuracy makes the
formats' own accuracy the accuracy setting.
Value
the previous values of the settings that were changed (all of
them with reset = TRUE), invisibly, as a list that restores them when
passed back to apa7_defaults() (e.g., with do.call())
Examples
old <- apa7_defaults(accuracy = .001)
# Tables as wide as the text on A4 paper with 1-inch margins
apa7_defaults(page_width = "a4")
# A two-column document: tables are as wide as a column unless a table
# asks for another width (e.g., table_width = "page" in apa_flextable())
apa7_defaults(table_width = "column")
# Restore the earlier accuracy
do.call(apa7_defaults, old)
# Reset to package defaults
apa7_defaults(reset = TRUE)
Tables ready for apa_flextable
Description
The tibbles returned by apa_anova(), apa_chisq(), apa_cor(), apa_descriptives(), apa_factor_cor(), apa_htest(), apa_loadings(), apa_means(), apa_contrasts(), apa_slopes(), apa_parameters(),
apa_performance(), apa_performance_comparison(), apa_reliability(), apa_collinearity(), apa_n_factors(), apa_publication_bias(), and apa_subgroups() have class
apa7_tbl. They are ordinary
tibbles for post-processing with dplyr, but in knitr and Quarto documents
they are rendered as an apa_flextable() automatically. In the console they
print as tibbles.
Usage
## S3 method for class 'apa7_tbl'
print(x, ...)
## S3 method for class 'apa7_tbl'
knit_print(x, ...)
Arguments
x |
an |
... |
arguments passed to the next method |
Details
The apa7.print option (also set with apa7_defaults(print = ))
controls this behavior:
-
"auto"(default): flextable in knitr/Quarto, tibble in the console. -
"flextable": flextable everywhere. -
"tibble": tibble everywhere.
To render with non-default settings, pass the table to apa_flextable()
explicitly, which always returns a flextable.
Value
x, invisibly, for print. A knit_asis or flextable output for knit_print.
Examples
fit <- lm(mpg ~ cyl + wt, data = mtcars)
# Prints as a tibble in the console
apa_parameters(fit)
# It is still a tibble, so it can be post-processed
apa_parameters(fit) |>
dplyr::filter(Variable != "Constant") |>
apa_flextable()
Citations in table notes
Description
Some table notes cite the articles that describe a method (e.g., the
trim-and-fill method in apa_publication_bias()). The references are in a
BibTeX file that comes with apa7, and apa7_write_bib() copies it to a
document's folder so that the citations in notes can be resolved and added
to the reference list.
Usage
apa7_write_bib(file = "apa7.bib", overwrite = TRUE)
apa7_bib()
Arguments
file |
path of the BibTeX file to write |
overwrite |
if |
Details
Citations in notes take one of two forms:
text: "(Duval & Tweedie, 2000)", which the author must add to the reference list by hand.
keys: Pandoc citation keys, "[@duvalTrimFillSimple2000]", which Pandoc's citeproc (and apaquarto) turns into formatted citations and reference-list entries, if the document's bibliography has the entries.
The form is set by the citations argument of apa_note(), or for all
notes by apa7_defaults(citations = ) (or options(apa7.citations = )):
"auto" (default), "keys", or
"text". With "auto", a citation is written as a key when a Quarto or
R Markdown document is being rendered and its bibliography (in the YAML
header, or for a whole Quarto project or folder in _quarto.yml or
_metadata.yml) has an entry with that key, and as text otherwise (e.g., in the
console, or in a table saved with flextable::save_as_docx()). So listing
the file written by apa7_write_bib() in the YAML header is enough:
--- bibliography: [references.bib, apa7.bib] ---
with apa7::apa7_write_bib() in the setup chunk. The citation keys are
those that the Better BibTeX extension for Zotero makes by default (e.g.,
eggerBiasMetaanalysisDetected1997), so entries exported from Zotero with
the same keys work, too.
Citations in notes from apa_flextable(note = TRUE) and the
apa-note chunk option of apaquarto are resolved when the document is
rendered. Citeproc does not see text that skips Pandoc (e.g., a flextable
saved directly to a Word file), so "auto" writes text there.
Value
apa7_write_bib() returns file, invisibly. apa7_bib() returns
the path of the BibTeX file that comes with apa7.
Examples
# In a document's setup chunk: apa7_write_bib("apa7.bib")
path <- apa7_write_bib(tempfile(fileext = ".bib"))
readLines(path, n = 8)
Format ANOVA tables in APA style
Description
Makes an analysis of variance source table with sums of squares, degrees of freedom, mean squares, F tests, p-values, and effect sizes. Values come from parameters::model_parameters(), and effect sizes come from the effectsize package (e.g., effectsize::eta_squared()).
Usage
apa_anova(
fit,
anova_parameters = c("Parameter", "Sum_Squares", "df", "Mean_Square", "F", "p",
"Effect_Size"),
effect_size = c("eta", "omega", "epsilon"),
partial = TRUE,
generalized = FALSE,
type = NULL,
ci = 0.95,
residual_label = "Error",
starred = NA,
bolded = NA,
column_formats = NULL,
...
)
## S3 method for class 'lm'
apa_anova(
fit,
anova_parameters = c("Parameter", "Sum_Squares", "df", "Mean_Square", "F", "p",
"Effect_Size"),
effect_size = c("eta", "omega", "epsilon"),
partial = TRUE,
generalized = FALSE,
type = NULL,
ci = 0.95,
residual_label = "Error",
starred = NA,
bolded = NA,
column_formats = NULL,
...
)
## S3 method for class 'aovlist'
apa_anova(
fit,
anova_parameters = c("Parameter", "Sum_Squares", "df", "Mean_Square", "F", "p",
"Effect_Size"),
effect_size = c("eta", "omega", "epsilon"),
partial = TRUE,
generalized = FALSE,
type = NULL,
ci = 0.95,
residual_label = "Error",
starred = NA,
bolded = NA,
column_formats = NULL,
...
)
## S3 method for class 'anova'
apa_anova(
fit,
anova_parameters = c("Parameter", "Sum_Squares", "df", "Mean_Square", "F", "p",
"Effect_Size"),
effect_size = c("eta", "omega", "epsilon"),
partial = TRUE,
generalized = FALSE,
type = NULL,
ci = 0.95,
residual_label = "Error",
starred = NA,
bolded = NA,
column_formats = NULL,
...
)
## S3 method for class 'afex_aov'
apa_anova(
fit,
anova_parameters = c("Parameter", "df", "df_error", "Mean_Square", "F", "p",
"Effect_Size"),
effect_size = c("eta", "omega", "epsilon"),
partial = TRUE,
generalized = TRUE,
type = NULL,
ci = 0.95,
residual_label = "Error",
starred = NA,
bolded = NA,
column_formats = NULL,
...
)
## S3 method for class 'merMod'
apa_anova(
fit,
anova_parameters = mixed_anova_parameters,
effect_size = NULL,
partial = TRUE,
generalized = FALSE,
type = NULL,
ci = 0.95,
residual_label = "Error",
starred = NA,
bolded = NA,
column_formats = NULL,
ddf = c("Kenward-Roger", "Satterthwaite"),
...
)
## Default S3 method:
apa_anova(fit, ...)
## S3 method for class 'mlm'
apa_anova(
fit,
anova_parameters = manova_anova_parameters,
effect_size = c("eta", "omega", "epsilon"),
partial = TRUE,
generalized = FALSE,
type = NULL,
ci = 0.95,
residual_label = "Error",
starred = NA,
bolded = NA,
column_formats = NULL,
test = c("Pillai", "Wilks", "Hotelling-Lawley", "Roy"),
univariate = FALSE,
...
)
## S3 method for class 'manova'
apa_anova(
fit,
anova_parameters = manova_anova_parameters,
effect_size = c("eta", "omega", "epsilon"),
partial = TRUE,
generalized = FALSE,
type = NULL,
ci = 0.95,
residual_label = "Error",
starred = NA,
bolded = NA,
column_formats = NULL,
test = c("Pillai", "Wilks", "Hotelling-Lawley", "Roy"),
univariate = FALSE,
...
)
## S3 method for class 'Anova.mlm'
apa_anova(
fit,
anova_parameters = manova_anova_parameters,
effect_size = c("eta", "omega", "epsilon"),
partial = TRUE,
generalized = FALSE,
type = NULL,
ci = 0.95,
residual_label = "Error",
starred = NA,
bolded = NA,
column_formats = NULL,
test = NULL,
univariate = FALSE,
...
)
Arguments
fit |
an |
anova_parameters |
columns to display. |
effect_size |
effect size to display: |
partial |
if |
generalized |
if |
type |
type of sums of squares for |
ci |
confidence level for the effect size interval, shown if |
residual_label |
label for residual (error) rows |
starred |
columns to star with significant p-values (e.g., |
bolded |
columns to bold, if significant |
column_formats |
column_formats object to format columns. If NULL, the default column_formats is used. |
... |
further arguments passed to |
ddf |
for linear mixed models, method of approximating the denominator degrees of freedom: |
test |
for multivariate models, the multivariate test statistic:
|
univariate |
for multivariate models, if |
Details
For repeated-measures models fit with aov(y ~ a * b + Error(id / b)), each error stratum is introduced by a heading row ("Between subjects" or "Within subjects"), and each stratum's error term follows its effects.
Model comparisons (e.g., anova(m1, m2)) are not ANOVA source tables. Use apa_performance_comparison() for them.
For afex models (afex::aov_car(), afex::aov_ez(), afex::aov_4()), each effect has its own error term, so the table shows each effect's degrees of freedom (df~effect~, df~error~), mean squared error (MSE), F, p, and effect size, as in afex's own nice() tables. Degrees of freedom and p-values reflect the sphericity correction set in afex (Greenhouse-Geisser by default), and generalized \eta^2 is the default effect size, as in afex.
For linear mixed models fit with lme4::lmer() or lmerTest::lmer(), F tests of the fixed effects come from the lmerTest package, which approximates the denominator degrees of freedom with Kenward-Roger's method (default, as in apa_parameters(), which requires the pbkrtest package) or Satterthwaite's method (ddf = "Satterthwaite"). Tests are Type III by default, as in lmerTest, whose Type III tests do not depend on how factors are coded. The table shows each effect's degrees of freedom (df~effect~, df~error~), F, and p. Sums of squares and effect sizes have no agreed-upon definition in mixed models, so they are not shown by default. With effect_size = "eta" (or "omega" or "epsilon"), partial effect sizes are computed from F and its degrees of freedom (e.g., effectsize::F_to_eta2()), which only approximates them. ANOVA tables made by lmerTest's anova() are displayed the same way. Generalized linear mixed models (lme4::glmer()) have no F tests; use apa_parameters() for them.
For multivariate analyses of variance, from stats::manova() or from
stats::lm() with several outcomes (lm(cbind(y1, y2) ~ x)), the table
has a row for each effect with its multivariate test statistic (Pillai's
trace by default; test chooses Wilks's lambda, the Hotelling–Lawley
trace, or Roy's largest root), its approximate F test (df~1~,
df~2~, p), and partial \eta^2, computed from the
approximate F and its degrees of freedom (e.g., effectsize::F_to_eta2()).
Sums of squares are sequential (Type I) by default, as in
stats::summary.manova(); type = 2 or 3 gives car::Anova() tests.
car::Anova() tables of such models (class Anova.mlm) are displayed the
same way. The intercept is not shown. With univariate = TRUE, the table
instead shows the univariate ANOVA of each outcome, under a heading row
for each outcome, as a follow-up to the multivariate tests.
Value
apa7_tbl (tibble)
References
Greenhouse, S. W., & Geisser, S. (1959). On methods in the analysis of profile data. Psychometrika, 24(2), 95–112. doi:10.1007/BF02289823
Huynh, H., & Feldt, L. S. (1976). Estimation of the Box correction for degrees of freedom from sample data in randomized block and split-plot designs. Journal of Educational Statistics, 1(1), 69–82. doi:10.3102/10769986001001069
Kenward, M. G., & Roger, J. H. (1997). Small sample inference for fixed effects from restricted maximum likelihood. Biometrics, 53(3), 983–997. doi:10.2307/2533558
Olejnik, S., & Algina, J. (2003). Generalized eta and omega squared statistics: Measures of effect size for some common research designs. Psychological Methods, 8(4), 434–447. doi:10.1037/1082-989X.8.4.434
Satterthwaite, F. E. (1946). An approximate distribution of estimates of variance components. Biometrics Bulletin, 2(6), 110–114. doi:10.2307/3002019
Pillai, K. C. S. (1955). Some new test criteria in multivariate analysis. The Annals of Mathematical Statistics, 26(1), 117–121. doi:10.1214/aoms/1177728599
Wilks, S. S. (1932). Certain generalizations in the analysis of variance. Biometrika, 24(3/4), 471–494. doi:10.1093/biomet/24.3-4.471
Examples
d <- mtcars
d$cyl <- factor(d$cyl)
d$am <- factor(d$am)
fit <- aov(mpg ~ cyl * am, data = d)
apa_anova(fit)
# Omega squared with a 90% confidence interval
apa_anova(
fit,
anova_parameters = c(
"Parameter", "Sum_Squares", "df", "Mean_Square", "F", "p",
"Effect_Size", "CI"
),
effect_size = "omega",
ci = .90
)
# Type 2 sums of squares (requires the car package)
if (requireNamespace("car", quietly = TRUE)) {
apa_anova(fit, type = 2)
}
if (requireNamespace("afex", quietly = TRUE)) {
data(obk.long, package = "afex")
fit_afex <- afex::aov_ez(
"id", "value", obk.long,
between = "treatment", within = "phase", fun_aggregate = mean
)
apa_anova(fit_afex)
}
if (requireNamespace("lme4", quietly = TRUE) &&
requireNamespace("lmerTest", quietly = TRUE) &&
requireNamespace("pbkrtest", quietly = TRUE)) {
fit_lmer <- lme4::lmer(
Reaction ~ Days + (Days | Subject),
data = lme4::sleepstudy
)
apa_anova(fit_lmer)
}
# Multivariate analysis of variance
if (requireNamespace("carData", quietly = TRUE)) {
fit_manova <- manova(
cbind(post.test.1, post.test.2, post.test.3) ~ group,
data = carData::Baumann
)
apa_anova(fit_manova)
apa_anova(fit_manova, test = "Wilks")
# Univariate follow-ups
apa_anova(fit_manova, univariate = TRUE)
}
Contingency table with a test of independence
Description
Makes an APA-style contingency table of two categorical variables: a row
for each level of variable and a column (or a pair of columns, with
percentages) for each level of by, with the counts in each cell. The
variables are tested for independence, and apa_note() writes the note,
with the result of the test and its effect size.
Usage
apa_chisq(
data,
variable = NULL,
by = NULL,
percent = c("column", "row", "total", "none"),
total = TRUE,
test = c("chisq", "fisher", "none"),
correct = TRUE,
effect_size = c("auto", "cramers_v", "phi", "none"),
percent_digits = 1,
labels = NULL,
format_variable_names = TRUE,
...
)
Arguments
data |
data frame |
variable |
variable whose levels are the rows of the table, unquoted
or quoted (e.g., |
by |
variable whose levels are the columns of the table, unquoted or
quoted. If |
percent |
percentages shown next to the counts: |
total |
if |
test |
|
correct |
if |
effect_size |
|
percent_digits |
number of decimal places of percentages |
labels |
named character vector of labels for |
format_variable_names |
format the names of variables that have no
label with the |
... |
deprecated arguments of earlier versions of |
Details
Like the other apa7 tables, the result is a tibble that is displayed as an
APA-style table in Quarto and R Markdown documents (see apa7_tbl). Pass
it to apa_flextable() to change its appearance, or use
apa_flextable(note = TRUE) to put the note below it.
Percentages are of each column's total (percent = "column", the
default), so each group of by can be described on its own; of each row's
total ("row"); or of the whole sample ("total"). With total = TRUE
(default), a "Total" row and column give the marginal counts.
The test is the chi-square test of independence (stats::chisq.test())
or Fisher's exact test (stats::fisher.test()). As in
stats::chisq.test(), 2 × 2 tables use Yates's continuity correction
unless correct = FALSE. When an expected count is below 5, the
chi-square approximation can be poor, and the note says so. The effect
size is \phi for 2 × 2 tables and Cramér's V otherwise
(without the small-sample adjustment), from the effectsize package.
Rows with a missing value of either variable are left out, and the note gives their number.
Value
apa7_tbl (tibble)
Examples
d <- data.frame(
Sex = factor(psych::sat.act$gender, levels = 1:2, labels = c("Men", "Women")),
Education = factor(psych::sat.act$education)
)
tbl <- apa_chisq(d, Education, by = Sex)
tbl
apa_note(tbl)
# Percentages of each row, and no totals
apa_chisq(d, Education, by = Sex, percent = "row", total = FALSE)
# Fisher's exact test instead of the chi-square test
apa_chisq(d[d$Education %in% c("0", "5"), ], Education, by = Sex, test = "fisher")
Collinearity diagnostics table
Description
Makes an APA-style table of the variance inflation factor (VIF) and
tolerance of each predictor in a regression model, as computed by
performance::check_collinearity().
Usage
apa_collinearity(
fit,
columns = c("VIF", "VIF_CI", "Tolerance"),
flag = NULL,
ci = 0.95,
format_variable_names = TRUE,
digits = 2,
...
)
Arguments
fit |
a regression model with at least two predictors (any model that
|
columns |
columns to display, in order: any of |
flag |
|
ci |
confidence level of the intervals |
format_variable_names |
if |
digits |
number of decimal places (unaffected by
|
... |
arguments passed to |
Details
The VIF of a predictor is the factor by which the variance of its
coefficient is inflated by its correlations with the other predictors.
Tolerance is 1/VIF, the proportion of the predictor's variance that the
other predictors do not explain. Common rules of thumb treat VIFs above 5
or 10 as signs of problematic collinearity; flag bolds them.
For terms with more than 1 degree of freedom (e.g., factors with more than
two levels), VIF is the generalized VIF (Fox & Monette, 1992), and
"SE_factor" is GVIF^{1/(2df)}, which is comparable
across terms with different degrees of freedom. The note names these terms.
In models with interactions, the VIFs of the interaction and its
component terms are high in part because product terms are correlated with
their components. This kind of collinearity does not affect the test of the
interaction, and centering the predictors reduces it. When any of these
VIFs is at or above flag (or 5, if flag is NULL), the note says so.
Models with several parts (e.g., the count and zero-inflation models of
pscl::zeroinfl() or glmmTMB::glmmTMB()) get a heading row for each
part.
Value
apa7_tbl (tibble)
References
Fox, J., & Monette, G. (1992). Generalized collinearity diagnostics. Journal of the American Statistical Association, 87(417), 178–183. doi:10.1080/01621459.1992.10475190
Examples
fit <- lm(mpg ~ wt + hp + disp + factor(cyl), data = mtcars)
apa_collinearity(fit)
# Bold VIFs of 10 or more, and show the note
apa_collinearity(fit, flag = 10) |>
apa_note()
APA-formatted correlation table
Description
APA-formatted correlation table
Usage
apa_cor(
data,
alpha = c(0.05, 0.01, 0.001),
digits = 2,
bold_significant = FALSE,
star_significant = TRUE,
significance_note = TRUE,
keep_empty_star_columns = TRUE,
summary_functions = list(M = mean, SD = stats::sd),
column_formats = NULL,
method = "pearson",
p_adjust = "none",
partial = FALSE,
...,
output,
note,
font_family,
font_size,
text_color,
border_color,
border_width,
line_spacing,
table_width,
p_value
)
Arguments
data |
data.frame or tibble with variables to be correlated, or the
output of |
alpha |
p-value thresholds for significance stars, from largest to
smallest (default: |
digits |
number of decimal places of the correlations (unaffected by
|
bold_significant |
if |
star_significant |
if |
significance_note |
if |
keep_empty_star_columns |
if |
summary_functions |
Any named list of functions that summarize data columns (e.g., |
column_formats |
|
method |
kind of correlation (e.g., |
p_adjust |
method of adjusting the p-values (and so the stars) for
multiple comparisons (e.g., |
partial |
if |
... |
other arguments passed to |
output, note, font_family, font_size, text_color, border_color, border_width, line_spacing, table_width |
deprecated. If any is given, a flextable is returned as in apa7 0.2.0,
with a warning (except |
p_value |
deprecated; use |
Details
apa_cor() computes the correlations with correlation::correlation().
By default, they are Pearson correlations of all pairwise complete
observations, and the stars are for unadjusted p-values. Use method,
p_adjust, partial, and the other arguments of
correlation::correlation() for other kinds of correlations. The column
names of data are the variable names in the table, and they can contain
spaces and symbols (e.g., "Reading comprehension") for every kind of
correlation: apa_cor() gives the variables internal names while the
correlations are computed. Logical columns are correlated as 0 and 1.
The output of correlation::correlation() can also be passed as data.
The table shows its correlations and p-values, and the summary columns
are computed from the data that correlation::correlation() keeps with
its results. Note that correlation::correlation() uses Holm's method by
default, so the stars are for adjusted p-values unless
p_adjust = "none", and that its partial and multilevel correlations do
not accept variable names with spaces. For those, use
apa_cor(data, partial = TRUE) instead.
apa_cor() returns an apa7_tbl, which is displayed as an APA-style
table in documents (see apa7_tbl). apa_note() writes its note: what
kind of correlations are shown (unless they are ordinary Pearson
correlations), how the p-values were adjusted for multiple comparisons,
and what the stars or bold values mean. With apaquarto, use the
apa-note chunk option (e.g., #| apa-note: !expr apa7::apa_note(tbl)).
Otherwise, use apa_flextable(tbl, note = TRUE). Correlations computed by
group, between two sets of variables, or with Bayesian methods are not yet
supported.
In apa7 0.2.0 and earlier, apa_cor() computed the correlations with
psych::corTest(). Its adjust argument is still accepted as
p_adjust, with a warning, and use = "complete" removes incomplete
rows, with a warning. Until apa7 0.3.0, apa_cor() returned a flextable
with the note below it, and it took the arguments that style a flextable.
These arguments still work, with a warning.
Value
apa7_tbl (tibble)
References
Benjamini, Y., & Hochberg, Y. (1995). Controlling the false discovery rate: A practical and powerful approach to multiple testing. Journal of the Royal Statistical Society: Series B (Methodological), 57(1), 289–300. doi:10.1111/j.2517-6161.1995.tb02031.x
Holm, S. (1979). A simple sequentially rejective multiple test procedure. Scandinavian Journal of Statistics, 6(2), 65–70.
Examples
tbl <- apa_cor(mtcars[, c("mpg", "am", "gear", "carb")])
tbl
apa_note(tbl)
# A flextable with the note below it, for documents without apaquarto
apa_flextable(tbl, note = TRUE)
# Significant correlations in bold instead of starred
apa_cor(mtcars[, c("mpg", "am", "gear", "carb")], bold_significant = TRUE)
# Partial Spearman correlations, with variable names that have spaces
d <- mtcars[, c("mpg", "wt", "hp")]
names(d) <- c("Miles per gallon", "Weight (1000 lbs)", "Gross horsepower")
apa_cor(d, method = "spearman", partial = TRUE)
# Output of correlation::correlation()
correlation::correlation(trees, method = "spearman") |>
apa_cor()
Descriptive statistics table ("Table 1")
Description
Makes an APA-style table describing a sample: for each continuous
variable, its mean and standard deviation (or median and interquartile
range), and for each categorical variable, the number and percentage of
respondents at each level. With by, there is a column for each group and
one for the whole sample, and group differences can be tested.
Usage
apa_descriptives(
data,
variables = NULL,
by = NULL,
total = TRUE,
continuous = "mean_sd",
categorical = NULL,
labels = NULL,
test = c("none", "auto", "chisq", "fisher"),
missing = c("note", "row"),
range = FALSE,
digits = 2,
percent_digits = 1,
format_variable_names = TRUE
)
Arguments
data |
data frame |
variables |
variables to describe, in order: unquoted or quoted names
(e.g., |
by |
grouping variable, unquoted or quoted (e.g., |
total |
if |
continuous |
how continuous variables are described: |
categorical |
numeric variables to treat as categorical, selected
like |
labels |
named character vector of variable labels (e.g., |
test |
tests of the differences between groups (requires |
missing |
where missing values are reported: |
range |
if |
digits |
number of decimal places of means, standard deviations,
medians, interquartile ranges, and ranges (unaffected by
|
percent_digits |
number of decimal places of percentages |
format_variable_names |
format variable names that have no label with
the |
Details
Numeric variables are continuous, and factors, character vectors, and
logical vectors are categorical (use categorical to treat numeric codes
as categories). Each categorical variable is introduced by a heading row,
with its levels indented below it, in factor level order (character
vectors are sorted).
Percentages are of the nonmissing responses. By default, apa_note() lists
the number of missing values of each variable that has any; with
missing = "row", each such variable gets a "Missing" row with the number
of missing values in each column instead. Rows whose by value is missing
are left out.
With range = TRUE, each continuous variable gets a "Range" row with its
minimum and maximum.
With test = "auto" (or "chisq" or "fisher"), a p column tests
group differences: Welch's t test
(two groups) or Welch's one-way ANOVA (stats::oneway.test(), more groups)
for variables described by their mean, the Kruskal-Wallis test for
variables described by their median, and the chi-square test of
independence (without continuity correction) for categorical variables.
When an expected count of a categorical variable's table is below 5, the
chi-square approximation can be poor, so with test = "auto" Fisher's
exact test is used for that variable instead, and the note names the
variables tested this way. test = "chisq" and test = "fisher" use one
test for every categorical variable.
Many journals discourage testing baseline differences in randomized
trials, so tests are not shown by default.
Value
apa7_tbl (tibble)
Examples
d <- mtcars
d$am <- factor(d$am, labels = c("Automatic", "Manual"))
d$cyl <- factor(d$cyl)
apa_descriptives(d, variables = c("mpg", "hp", "cyl"), by = "am")
# Ranges and rows of missing values
d$hp[c(3, 8)] <- NA
apa_descriptives(d, variables = c("mpg", "hp", "cyl"), by = "am",
range = TRUE, missing = "row")
# Unquoted names and tidyselect helpers work too
apa_descriptives(d, variables = c(mpg, starts_with("c")), by = am)
# Medians for skewed variables, and tests of group differences
apa_descriptives(
d,
variables = c(mpg, hp, cyl),
by = am,
continuous = c(hp = "median_iqr"),
test = "auto"
)
Factor correlation table
Description
Makes an APA-style table of the correlations among factors (or
components) from an obliquely rotated solution: a psych::fa() or
psych::principal() object, or the output of
parameters::factor_analysis() or parameters::principal_components().
For a lavaan model, the table shows the correlations among the latent
variables in the fully standardized solution. When latent variables are
linked by regression paths, these correlations are implied by the model.
Usage
apa_factor_cor(fit, factor_names = NULL, digits = 2)
Arguments
fit |
a |
factor_names |
names for the factors. Either an unnamed character vector in the order the factors appear in the table (psych orders factors by variance explained), or a named vector that maps the original names to new names (e.g., |
digits |
number of decimal places (unaffected by
|
Details
The factors are numbered in the first column, and the numbers are used as
column headers. Only the lower triangle is shown. The factors are in the
same order as in apa_loadings().
Value
apa7_tbl (tibble)
Examples
fit <- psych::fa(Harman74.cor$cov, 4, fm = "pa", rotate = "oblimin")
apa_factor_cor(
fit,
factor_names = c("Verbal", "Spatial", "Speed", "Memory")
)
Convert data to flextable consistent with APA style
Description
The apa_flextable function formats a data frame and converts it to a
flextable in APA style. See Details for the steps it takes.
Usage
apa_flextable(
data,
row_title_column = NULL,
row_title_align = "left",
row_title_prefix = "",
row_title_sep = " ",
row_title_border = list(color = "gray20", style = "solid", width = 1),
left_column_padding = 20,
col_keys = colnames(data),
cwidth = 0.75,
cheight = 0.25,
header_align_vertical = c("top", "middle", "bottom"),
separate_headers = TRUE,
apa_style = TRUE,
font_family = NULL,
font_size = NULL,
text_color = "black",
border_color = "black",
border_width = 0.5,
line_spacing = NULL,
horizontal_padding = 3,
table_align = "left",
layout = "autofit",
table_width = NULL,
markdown = TRUE,
markdown_header = markdown,
markdown_body = markdown,
no_markdown_columns = NULL,
no_markdown_columns_header = NULL,
no_format_columns = NULL,
auto_format_columns = TRUE,
column_formats = NULL,
pretty_widths = TRUE,
add_breaks_between_spanners = TRUE,
note = NULL,
...
)
Arguments
data |
data.frame or tibble |
row_title_column |
column whose values become heading rows that group the rows below them (unquoted or quoted name, or a tidyselect helper). The column itself is not displayed. Rows should already be sorted by it. |
row_title_align |
alignment of the heading rows: |
row_title_prefix |
text placed before each heading (e.g., |
row_title_sep |
text between |
row_title_border |
border drawn around each group of rows: a list of
|
left_column_padding |
left padding of the first column's body rows, in points, which indents them under left-aligned heading rows (only used with |
col_keys |
columns to display, in order (default: all columns of
|
cwidth, cheight |
initial cell width and height in inches, passed to
|
header_align_vertical |
vertical alignment of header text when header
cells differ in height: |
separate_headers |
if |
apa_style |
if |
font_family |
font family (e.g., |
font_size |
font size, in points. If |
text_color |
color of the text: an R color name (e.g., |
border_color |
color of the rules, in the same forms as |
border_width |
width of the rules, in points (default: 0.5) |
line_spacing |
spacing between lines of the header and body (e.g., 2
for double spacing or 1 for single spacing). If |
horizontal_padding |
space to the left and right of each cell's contents, in points (default: 3) |
table_align |
alignment of the table on the page: |
layout |
|
table_width |
width of the table, in the same forms in every apa7
function: a proportion from 0 to 1 of the default width (the full width
of a portrait page unless changed with |
markdown |
if |
markdown_header, markdown_body |
whether the header or the body is
converted from markdown (both default to |
no_markdown_columns |
body columns whose text is shown as it is, not converted from markdown (unquoted or quoted names, or tidyselect helpers) |
no_markdown_columns_header |
column headers that are not treated as
markdown. If |
no_format_columns |
Column name or tidyselect function. selected columns are not formatted. Columns named in a |
auto_format_columns |
if |
column_formats |
a |
pretty_widths |
if |
add_breaks_between_spanners |
if |
note |
table note placed below the table, after "Note.". The note is single-spaced. If |
... |
passed to |
Details
With a few minor details omitted, apa_flextable does roughly this:
Adds a break column between adjacent column spanners, if
add_breaks_between_spanners = TRUEandseparate_headers = TRUE. A break column is a narrow blank column without borders, so the rules under adjacent spanners do not touch.If
auto_format_columns = TRUE, turns columns of whole numbers (e.g., degrees of freedom) into integers so that they have no decimals. Then formats the columns withapa_format_columns(). Columns named inno_format_columns, or in a"no_format_columns"attribute of the data (set by functions such asapa_loadings()), are left as they are.Makes the flextable. With
row_title_column, it first restructures the data withflextable::as_grouped_data(), and each row title gets a rule above it (row_title_border).Separates the headers into spanners and deckered heads, if
separate_headers = TRUE.Left-aligns the first column and centers the columns of numbers.
Applies
apa_style()to style the table and convert markdown, ifapa_style = TRUE.Aligns the row titles (
row_title_align) and indents the rows under them (left_column_padding).Sets the column widths with
pretty_widths(), ifpretty_widths = TRUE.Lines up numbers padded by
align_chr()on their decimal points.Draws a rule above the rows named in a
"rule_above"attribute of the data (set by functions such asapa_loadings()andapa_chisq()).Adds the note, if
noteis given. It is added last so that a long note does not widen the columns.
For a step-by-step version of this process, see the article Building Tables by Hand.
Value
flextable::flextable
References
American Psychological Association. (2020). Publication manual of the American Psychological Association (7th ed.). doi:10.1037/0000165-000
Examples
# Means and SDs, with a heading row for each transmission type
d <- mtcars
d$am <- factor(d$am, levels = 0:1, labels = c("Automatic", "Manual"))
d[, c("am", "mpg", "hp", "wt")] |>
tidyr::pivot_longer(-am, names_to = "Variable") |>
dplyr::summarise(Mean = mean(value), SD = sd(value), .by = c(am, Variable)) |>
dplyr::arrange(am) |>
apa_flextable(row_title_column = am, row_title_align = "center")
# Widths for a landscape page, one column of a two-column page, and 10 cm
fit <- lm(mpg ~ wt + hp, data = mtcars)
apa_flextable(apa_parameters(fit), table_width = "landscape")
apa_flextable(apa_parameters(fit), table_width = "column")
apa_flextable(apa_parameters(fit), table_width = c(cm = 10))
Format data columns
Description
apa_format_columns() formats the columns of a data frame of results and
renames their headers in APA style, using a set of column_formats().
apa_flextable() calls it when auto_format_columns = TRUE.
Usage
apa_format_columns(
data,
column_formats = NULL,
no_format_columns = NULL,
rename_headers = TRUE,
latex_headers = FALSE,
format_separated_headers = TRUE,
sep = "_",
accuracy = NULL
)
Arguments
data |
data set (data.frame or tibble) |
column_formats |
|
no_format_columns |
Column name or tidyselect function. selected columns are not formatted |
rename_headers |
if |
latex_headers |
if |
format_separated_headers |
if |
sep |
separator for separated headers (default is "_") |
accuracy |
numeric (default: NULL, uses the current default accuracy set with |
Details
Each column is matched by name to a column_format() in column_formats
(e.g., p, SE, beta, or R2). The values of a matched column are
formatted by the format's formatter, and its name is replaced by the
format's markdown header (e.g., beta becomes *β*), or by its LaTeX
header if latex_headers = TRUE. Columns without a format, and columns
named in no_format_columns, are left as they are.
If format_separated_headers = TRUE (default), a column name with a
separator (sep, an underscore by default) is matched by its last part, so
Model 1_R2 is formatted like R2 and becomes Model 1_*R*^2^. In
apa_flextable(), the part before the separator becomes a column spanner.
Format names that contain an underscore themselves (e.g., R2_adjusted) are
matched whole.
A few columns are matched by a pattern or combined:
-
CI,CI_low, andCI_high(e.g., fromparameters::parameters()) become a single column of intervals, with a header such as "95% CI" that gives the confidence level stored inCI. Prefixed columns are combined the same way for each column spanner (e.g.,Model 1_CI,Model 1_CI_low, andModel 1_CI_highbecomeModel 1_95% CI). ACIcolumn without its bounds is left as it is. If there are
tanddf_errorcolumns, the degrees of freedom are moved into thetheader (e.g., t(28)), anddf_erroris dropped.A column named like
t(28)is formatted with thet_dfformat (and gets the header t(28)), and one named like90% CIwith theCI_percentformat.
To see the default formats, run column_formats()@get_tibble. The article
Building Tables by Hand
shows how to change them.
Value
tibble
Examples
lm(mpg ~ cyl + wt, data = mtcars) |>
parameters::parameters() |>
apa_format_columns() |>
apa_flextable()
Format hypothesis tests in APA style
Description
Runs t tests, Wilcoxon tests, correlation tests, or chi-square tests of
independence on the variables in a data frame and makes a table with one row
per outcome variable: descriptive statistics, the test statistic, its
degrees of freedom, the p-value, and an effect size with its confidence
interval. Tests come from the stats package (e.g., stats::t.test()), and
effect sizes are computed from the data with the effectsize package (e.g.,
effectsize::cohens_d()).
Usage
apa_htest(
data,
formula,
test = c("t", "wilcoxon", "cor", "chisq"),
effect_size = NULL,
ci = 0.95,
var_equal = FALSE,
mu = 0,
method = c("pearson", "spearman", "kendall"),
descriptives = TRUE,
pair_labels = NULL,
starred = NA,
bolded = NA,
column_formats = NULL,
...
)
Arguments
data |
data frame, or test results already computed: an |
formula |
two-sided formula with outcome variables on the left and a
grouping or predictor variable on the right. Several outcomes are joined
with |
test |
type of test:
|
effect_size |
effect size to display. If For paired t tests, Cohen's d is d~av~ ( |
ci |
confidence level of the effect size interval (for correlation tests, the interval of Pearson's r). Intervals are two-sided. |
var_equal |
if |
mu |
value that one-sample tests compare each variable with (for two-group tests, the hypothesized difference in location) |
method |
correlation coefficient: |
descriptives |
if |
pair_labels |
for paired tests, labels of the first and second
variable of each pair, used as the headings above their descriptive
statistics (e.g., |
starred |
columns to star with significant p-values (e.g., |
bolded |
columns to bold, if significant |
column_formats |
column_formats object to format columns. If NULL, the default column_formats is used. |
... |
further arguments passed to the test function (e.g.,
|
Details
Each test uses the rows in which both the outcome and the grouping (or predictor) variable are observed. For two-group tests, the grouping variable must have exactly two observed values, and differences are the first group (in factor level order) minus the second. Paired tests use the rows in which both variables of the pair are observed, and differences are the first variable minus the second.
Effect sizes are computed from the data rather than from the test statistic, so Cohen's d for Welch's test is exact rather than approximated from t.
Use apa_note() to write a table note that says which tests were done, how
the effect size was computed, and what the abbreviations stand for.
Value
apa7_tbl (tibble)
Test results
htest objects keep the test statistic, its degrees of freedom, and the
p-value, but not the data, so formula and the arguments that control
the tests are not used, and effect sizes are computed from what the
objects keep:
One-sample and paired t tests: Cohen's d (d~z~ for paired tests) is exactly
t/\sqrt{n}, with an exact interval from the noncentral t distribution.Two-sample t tests: Cohen's d is approximated as
2t/\sqrt{df}(effectsize::t_to_d()), which assumes groups of equal size, and the note says so. For exact values, giveapa_htest()the data instead.Correlation tests: the correlation and, for Pearson's r, its interval and the sample size.
Chi-square tests of independence: Cramér's V,
\phi, or Cohen's w, computed from the observed table that the object keeps.Wilcoxon tests and chi-square goodness-of-fit tests: no effect size, because the objects do not keep the sample sizes.
The rows are labeled by the list's names or, if unnamed, by the objects' data names (e.g., "mpg by am"). The table has no descriptive statistics.
References
Lakens, D. (2013). Calculating and reporting effect sizes to facilitate cumulative science: A practical primer for t-tests and ANOVAs. Frontiers in Psychology, 4, Article 863. doi:10.3389/fpsyg.2013.00863
Examples
# Welch's t tests with Cohen's d
d <- mtcars
d$am <- factor(d$am, labels = c("Automatic", "Manual"))
apa_htest(d, mpg + hp + qsec ~ am)
# Student's t test with Hedges' g
apa_htest(d, mpg ~ am, var_equal = TRUE, effect_size = "hedges_g")
# One-sample t test
apa_htest(d, mpg ~ 1, mu = 20)
# Paired t test with d_av
d_sleep <- data.frame(drug1 = sleep$extra[1:10], drug2 = sleep$extra[11:20])
apa_htest(d_sleep, Pair(drug1, drug2) ~ 1)
# Wilcoxon rank-sum tests with rank-biserial correlations
apa_htest(d, mpg + hp ~ am, test = "wilcoxon", exact = FALSE)
# Correlation tests
apa_htest(d, mpg + hp + qsec ~ wt, test = "cor")
# Chi-square tests of independence with Cramer's V
d$cyl <- factor(d$cyl)
d$vs <- factor(d$vs, labels = c("V-shaped", "Straight"))
tbl <- apa_htest(d, cyl + vs ~ am, test = "chisq")
tbl
apa_note(tbl)
# Test results already computed
apa_htest(t.test(mpg ~ am, data = d))
apa_htest(list(
Weight = cor.test(d$mpg, d$wt),
Displacement = cor.test(d$mpg, d$disp)
))
Factor loadings table
Description
Makes an APA-style table of factor loadings from an exploratory factor
analysis, a principal components analysis, or a confirmatory factor
analysis fit with lavaan.
Usage
apa_loadings(
fit,
sort_loading = TRUE,
min_loading = 0.2,
factor_names = NULL,
variance = FALSE,
communality = FALSE,
uniqueness = FALSE,
complexity = FALSE,
bold_max = FALSE,
format_variable_names = TRUE,
digits = 2
)
Arguments
fit |
a |
sort_loading |
sort the rows so that variables are grouped by the factor with their largest loading, and by the size of that loading within each factor (as in |
min_loading |
minimum absolute loading to display. Use |
factor_names |
names for the factors. Either an unnamed character vector in the order the factors appear in the table (psych orders factors by variance explained), or a named vector that maps the original names to new names (e.g., |
variance |
if |
communality |
add a communality (h^2^) column |
uniqueness |
add a uniqueness (u^2^) column |
complexity |
add a column with Hofmann's complexity index |
bold_max |
bold the largest displayed loading (in absolute value) in each row |
format_variable_names |
format the variable names with the |
digits |
number of decimal places for loadings (unaffected by
|
Details
fit can be a psych::fa() or psych::principal() object, or the output
of parameters::factor_analysis() or parameters::principal_components().
For the parameters functions, the loadings come from the underlying model,
so their sort and threshold settings do not matter: use sort_loading
and min_loading instead. Unrotated parameters::principal_components()
output wraps a stats::prcomp() model. Its loadings are the correlations
between the variables and the components when the variables are
standardized (the default, standardize = TRUE).
For a lavaan::cfa() or lavaan::sem() model, the loadings are the fully
standardized estimates (as in lavaan::standardizedSolution()), and loadings
fixed at 0 are left blank. As for exploratory analyses, the rows are sorted
by the factor with each variable's largest loading and by the size of that
loading (use sort_loading = FALSE to keep the order of the model syntax).
Every estimated loading is shown, unless min_loading is set. The
communality is the proportion of an indicator's variance explained
by the factors (R^2), and the uniqueness is its standardized
residual variance. Variable and factor names are shown as written in the
model, with the first letter capitalized and underscores replaced by
spaces. Loadings of higher-order factors (regressions among latent
variables) are not part of this table; see apa_parameters(). Multiple-group
models are not yet supported.
Loadings smaller in absolute value than min_loading are left blank. With
bold_max = TRUE, the largest displayed loading in each row is bolded.
Rows for variance explained (variance = TRUE) are added below the
loadings: the sum of squared loadings, the proportion of total variance,
and the cumulative proportion (the last only when there is more than one
factor). apa_flextable() draws a rule above these rows. With an oblique
rotation the factors are correlated, so the variance explained by each
factor overlaps with the others and the cumulative proportion is only
approximate. Report the factor correlations with apa_factor_cor().
The variable names are formatted (e.g., title case) when
format_variable_names = TRUE. Either way, apa_flextable() leaves the
Variable column as it is, so item text is never changed again when the
table is rendered.
Value
apa7_tbl (tibble)
Examples
fit <- psych::fa(Harman74.cor$cov, 4, fm = "pa", rotate = "varimax")
apa_loadings(
fit,
factor_names = c("Verbal", "Spatial", "Speed", "Memory")
)
# With rows for variance explained and bolded primary loadings
apa_loadings(fit, variance = TRUE, communality = TRUE, bold_max = TRUE)
# Principal components
psych::principal(Harman74.cor$cov, 4) |>
apa_loadings()
# parameters output
parameters::principal_components(mtcars[, 1:7], n = 2) |>
apa_loadings()
# Confirmatory factor analysis
if (requireNamespace("lavaan", quietly = TRUE)) {
hs_model <- "visual =~ x1 + x2 + x3
textual =~ x4 + x5 + x6
speed =~ x7 + x8 + x9"
fit_cfa <- lavaan::cfa(hs_model, data = lavaan::HolzingerSwineford1939)
apa_loadings(fit_cfa, communality = TRUE)
apa_factor_cor(fit_cfa)
}
Estimated marginal means, contrasts, and slopes tables
Description
Makes APA-style tables of estimated marginal means, contrasts between them (e.g., pairwise comparisons after an ANOVA), and simple slopes (e.g., to probe a moderation effect), computed with the modelbased package.
Usage
apa_means(
fit,
by = NULL,
...,
starred = NA,
bolded = NA,
column_formats = NULL,
format_variable_names = TRUE
)
apa_contrasts(
fit,
contrast = NULL,
by = NULL,
...,
effect_size = NULL,
sd = NULL,
starred = NA,
bolded = NA,
column_formats = NULL,
format_variable_names = TRUE
)
apa_slopes(
fit,
trend = NULL,
by = NULL,
...,
johnson_neyman = NULL,
starred = NA,
bolded = NA,
column_formats = NULL,
format_variable_names = TRUE
)
Arguments
fit |
a model, or output of |
by |
variables whose levels (or values) the estimates are computed at
(e.g., |
... |
other arguments passed to the modelbased function when |
starred |
columns to which significance stars are added (e.g., |
bolded |
columns that are bolded when p |
column_formats |
|
format_variable_names |
if |
contrast |
variable whose levels (or values) are compared (e.g.,
|
effect_size |
in |
sd |
in |
trend |
predictor whose slopes are estimated (e.g., |
johnson_neyman |
in |
Details
fit is either a model or the output of modelbased::estimate_means(),
modelbased::estimate_contrasts(), or modelbased::estimate_slopes().
With a model, by, contrast, trend, and the arguments in ... (e.g.,
p_adjust) are passed to the modelbased function, so
apa_contrasts(fit, contrast = "group", p_adjust = "holm") is the same as
apa_contrasts(modelbased::estimate_contrasts(fit, contrast = "group", p_adjust = "holm")).
Rows are labeled by the levels of the last focal variable (in
apa_means()), by the levels compared (in apa_contrasts(), e.g.,
"6 - 4"), or by the levels of the moderator (in apa_slopes()).
Any other variables in by get heading rows, with the rows below them
indented. Numeric levels (e.g., values of a continuous moderator) are
rounded to 2 decimals.
Values set with a modelbased shortcut are named, with the value in
parentheses: "x=[sd]" (or "x=[meansd]") gives "-1SD",
"M", and "+1SD"; "x=[mad]" gives "-1MAD", "Mdn", and
"+1MAD"; "x=[fivenum]" gives "Min", "Q~1~", "Mdn", "Q~3~",
and "Max"; "x=[quartiles]" gives "Q~1~", "Mdn", and "Q~3~";
and "x=[minmax]" gives "Min" and "Max". Contrasts between such values
(e.g., contrast = "x=[sd]") are labeled by name (e.g.,
"+1SD - M"), and the note gives the values. With a model, a
numeric variable named in by without values (e.g., by = "x") is set to
its mean and 1 SD above and below it, as with by = "x=[sd]" (rather
than the modelbased default of 10 values, which suits plots better than
tables).
apa_note() says what the values are, how the other predictors were held
constant, on which scale the estimates are (for models with a link
function, such as logistic regression), which level was subtracted from
which, and how p-values were adjusted for multiple comparisons.
In apa_contrasts(), contrasts from models of continuous outcomes with an
identity link (e.g., lm() and aov()) get Cohen's d with its
confidence interval: each difference divided by the model's residual
standard deviation (\hat{\sigma}), as in
emmeans::eff_size(). The interval accounts for the uncertainty in
\hat{\sigma}. For mixed models, there is no single right
standard deviation to divide by, so d is shown only when it is given with
sd (e.g., the
square root of the sum of the variance components and the residual
variance). d is not computed for logistic and other generalized linear
models.
In apa_slopes(), when the slope of trend depends on a single
continuous moderator in by through a two-way interaction (e.g.,
lm(y ~ x * m)), the note gives the Johnson-Neyman intervals (Johnson &
Neyman, 1936): the values of the moderator, within its observed range, at
which the slope is significant. The boundaries are computed exactly from
the coefficients and their covariance matrix (the values of the moderator
at which the slope's test statistic equals its critical value), with t
and the residual degrees of freedom for lm() models and the normal
distribution for other models (e.g., mixed models). They are not computed
for models with a link function (e.g., logistic regression), or when the
slope also depends on other variables (e.g., a three-way interaction).
Bayesian models are not yet supported.
Value
apa7_tbl (tibble)
References
Benjamini, Y., & Hochberg, Y. (1995). Controlling the false discovery rate: A practical and powerful approach to multiple testing. Journal of the Royal Statistical Society: Series B (Methodological), 57(1), 289–300. doi:10.1111/j.2517-6161.1995.tb02031.x
Holm, S. (1979). A simple sequentially rejective multiple test procedure. Scandinavian Journal of Statistics, 6(2), 65–70.
Johnson, P. O., & Neyman, J. (1936). Tests of certain linear hypotheses and their application to some educational problems. Statistical Research Memoirs, 1, 57–93.
Kramer, C. Y. (1956). Extension of multiple range tests to group means with unequal numbers of replications. Biometrics, 12(3), 307–310. doi:10.2307/3001469
Tukey, J. W. (1994). The problem of multiple comparisons. In H. I. Braun (Ed.), The collected works of John W. Tukey: Vol. VIII. Multiple comparisons, 1948–1983 (pp. 1–300). Chapman & Hall.
Examples
if (requireNamespace("modelbased", quietly = TRUE) &&
requireNamespace("marginaleffects", quietly = TRUE)) {
fit <- lm(Sepal.Width ~ Species * Sepal.Length, data = iris)
# Means of each species, with sepal length held at its mean
apa_means(fit, by = "Species")
# Pairwise comparisons, with Holm-adjusted p-values
apa_contrasts(fit, contrast = "Species", p_adjust = "holm")
# Simple slopes of sepal length in each species
apa_slopes(fit, trend = "Sepal.Length", by = "Species")
# The output of modelbased works, too
modelbased::estimate_contrasts(fit, contrast = "Species") |>
apa_contrasts() |>
apa_note()
}
Factor retention table
Description
Makes an APA-style table of how many factors (or components) each method
suggests retaining, as computed by parameters::n_factors().
Usage
apa_n_factors(
fit,
table = c("methods", "agreement"),
bold_consensus = TRUE,
format_method_names = TRUE,
components = NULL,
...
)
Arguments
fit |
the output of |
table |
|
bold_consensus |
if |
format_method_names |
if |
components |
if |
... |
arguments passed to |
Details
fit can be the output of parameters::n_factors(), or a data frame, in
which case parameters::n_factors() is run with the arguments in ...
(e.g., type = "PCA" for components, or package to choose the packages
whose methods are used: by default nFactors and psych, which must be
installed).
With table = "methods" (default), each row is a method and the number of
factors it suggests, in the order of the number of factors. The numbers
supported by the most methods are bolded (bold_consensus = TRUE). With
table = "agreement", each row is a number of factors suggested by at
least one method, with the number of methods that suggest it and the
cumulative proportion of variance explained by that many factors.
The note names the number of factors supported by the most methods and those methods. Methods differ greatly in how well they work, and they often disagree: parallel analysis and Velicer's minimum average partial (MAP) test are generally recommended, while the Kaiser criterion (eigenvalues greater than 1) and the chi-square tests (Bartlett's, Anderson's, and Lawley's) tend to suggest too many factors. The number of methods that agree is not by itself a good reason to retain a number of factors.
Value
apa7_tbl (tibble)
References
Horn, J. L. (1965). A rationale and test for the number of factors in factor analysis. Psychometrika, 30(2), 179–185. doi:10.1007/BF02289447
Kaiser, H. F. (1960). The application of electronic computers to factor analysis. Educational and Psychological Measurement, 20(1), 141–151. doi:10.1177/001316446002000116
Velicer, W. F. (1976). Determining the number of components from the matrix of partial correlations. Psychometrika, 41(3), 321–327. doi:10.1007/BF02293557
Examples
if (requireNamespace("nFactors", quietly = TRUE)) {
d <- na.omit(psych::bfi[, 1:25])
apa_n_factors(d)
# One row per suggested number of factors
nf <- parameters::n_factors(d)
apa_n_factors(nf, table = "agreement")
apa_n_factors(nf) |>
apa_note()
}
Write a table note
Description
Makes the text of an APA-style table note from what a table function recorded about how the table was made. The text is a starting point: edit it or add to it as needed.
Usage
apa_note(x, collapse = " ", citations = NULL)
Arguments
x |
a table made by an apa7 table function: |
collapse |
string that joins the sentences. Use |
citations |
how articles cited in the note are written: |
Details
For apa_anova() tables, the note can say
which type of sums of squares was used,
which effects have sphericity-corrected degrees of freedom (for
afexmodels, only effects involving a within-subjects factor with more than two levels are corrected),what the effect size (and MSE, for
afexmodels) stands for, andwhat stars or bold values mean.
For apa_loadings() tables, the note can say
how the factors were extracted and rotated (e.g., "Principal axis factoring with oblimin rotation"), and that loadings after an oblique rotation are pattern coefficients,
which loadings are omitted (
min_loading) or bolded (bold_max),what the h^2^, u^2^, and Complexity columns stand for, and
that the cumulative proportion of variance is approximate when the factors are correlated.
For confirmatory factor analyses fit with lavaan, the note instead gives
the sample size and estimator, says that the loadings are standardized, and
says that blank cells are loadings fixed at 0.
For apa_descriptives() tables, the note says which statistics are
shown, lists missing values, and names the tests of group differences.
For apa_means(), apa_contrasts(), and apa_slopes() tables, the note
says what the values are, how the other predictors were held constant, on
which scale the estimates are, which level was subtracted from which, and
how p-values were adjusted for multiple comparisons.
For apa_collinearity() tables, the note names terms with generalized
VIFs, explains the VIFs of interaction terms, defines tolerance, and
says which VIFs are bolded.
For apa_reliability() tables, the note gives the number of respondents,
says which items were reverse-scored and how scale scores were computed,
and defines the statistics.
For apa_factor_cor() tables, the note says how the factors were
extracted and rotated (for lavaan models, the sample size, the
estimator, and that the correlations are standardized).
For apa_htest() tables, the note can say
which tests were done (e.g., Welch's t tests) and what the groups were compared with or the variables were correlated with,
that p-values are one-sided, if they are,
how Cohen's d (or Hedges' g) was standardized,
what the effect size and its confidence interval stand for, and
what stars or bold values mean.
For apa_parameters() tables of regression models (lm, glm, polr,
clm, multinom, zeroinfl, hurdle, lme4, glmmTMB, and nlme models, or a list of models), the note can say
which robust standard errors were used (e.g.,
vcov = "HC3"),how the degrees of freedom of mixed-model t tests were approximated (Kenward-Roger or Satterthwaite),
that ordinal-model thresholds are not tested,
the scale of the zero-inflation and dispersion coefficients of
glmmTMBmodels,the residual correlation structure and variance function of
nlme::lmemodels,the reference category of multinomial models (
nnet::multinom),the count distribution and the meaning of the zero model of zero-inflated and hurdle models (
pscl),the effect-size measure and model of meta-analyses (
metafor::rma) and, for tables of studies, the test of the pooled estimate, its prediction interval, and the test of heterogeneity,what the standardized coefficient (
\beta), exponentiated coefficient (e.g., OR), confidence interval, and model-comparison (e.g.,\Delta R^2) columns stand for, andwhat stars or bold values mean.
Abbreviations are defined from the abbreviation slot of each column's
column_format(), so a note defines every abbreviated header that has a
definition. To define another header, or to change a definition, set the
slot in the column_formats passed to the table function (or set the
default with apa7_defaults()):
cf <- column_formats()
cf$Sum_Squares@abbreviation <- "sum of squares"
apa_anova(fit, anova_parameters = c("Parameter", "Sum_Squares", "df", "F", "p"),
column_formats = cf)
The sentences are in APA order: general notes first, then probability notes.
The text does not start with "Note." because apaquarto adds it. With
apaquarto, make the table in one
chunk and display it in another, using the note as the apa-note chunk
option. Write apa7::apa_note() there, because in documents with cached
chunks, chunk options can be evaluated before library(apa7) takes effect:
```{r}
#| label: anova-fit
tbl <- apa_anova(fit, type = 3)
```
```{r}
#| label: tbl-anova
#| tbl-cap: Analysis of Variance
#| apa-note: !expr apa7::apa_note(tbl)
tbl
```
The information is stored in an "apa_note" attribute of the table. dplyr
functions such as mutate() and filter() keep it, but some operations
(e.g., bind_rows() and joins) drop it, so call apa_note() on the
table that the table function returned.
Value
character. Comparison signs (e.g., "=" in "N = 32") have non-breaking spaces (U+00A0) on both sides, so that a statistic is never split across lines.
Examples
d <- mtcars
d$cyl <- factor(d$cyl)
d$am <- factor(d$am)
fit <- aov(mpg ~ cyl * am, data = d)
tbl <- apa_anova(fit, starred = "F")
apa_note(tbl)
# Descriptive statistics with tests of group differences
d$Transmission <- factor(d$am, labels = c("Automatic", "Manual"))
apa_descriptives(d, variables = c(mpg, hp), by = Transmission, test = "auto") |>
apa_note()
# Factor analysis
fit_fa <- psych::fa(Harman74.cor$cov, 4, fm = "pa", rotate = "varimax")
apa_loadings(fit_fa, min_loading = .3, communality = TRUE) |>
apa_note()
# Regression
lm(mpg ~ cyl + wt, data = mtcars) |>
apa_parameters(starred = "p") |>
apa_note()
p-value in APA format
Description
p-value in APA format
Usage
apa_p(
p,
inline = FALSE,
markdown = TRUE,
min_digits = 2,
max_digits = 3,
align = FALSE
)
Arguments
p |
probability |
inline |
if |
markdown |
if |
min_digits |
minimum number of digits to round to. Default is 2. |
max_digits |
maximum number of digits to round to. Default is 3. |
align |
decimal alignment if |
Value
character vector
Examples
# Values less than .001 are <.001
apa_p(.0002)
# Values between .001 and .01 are rounded to 3 digits
apa_p(.002)
# Values between .01 and .995 are rounded to 2 digits
apa_p(.02)
apa_p(.22)
apa_p(.994)
# Values above .995 are >.99
apa_p(.999)
# Rounding to 3 digits
apa_p(.2341, min_digits = 3)
apa_p(.0123, min_digits = 3)
apa_p(.00123, min_digits = 3)
apa_p(.000123, min_digits = 3)
apa_p(.991, min_digits = 3)
apa_p(.9991, min_digits = 3)
apa_p(.9995, min_digits = 3)
Make star notes for p-values
Description
Make star notes for p-values
Usage
apa_p_star_note(alpha = c(0.05, 0.01, 0.001), first_alpha_marginal = FALSE, x)
Arguments
alpha |
vector of alpha values (p-value thresholds), from largest to smallest. Each gets one more star. |
first_alpha_marginal |
if TRUE, the first alpha value is treated as marginal and gets a dagger instead of a star |
x |
deprecated; use |
Value
character vector
Examples
apa_p_star_note()
apa_p_star_note(alpha = c(0.10, 0.05, 0.01, 0.001),
first_alpha_marginal = TRUE)
format model parameters in APA style
Description
format model parameters in APA style
Usage
apa_parameters(
fit,
predictor_parameters = c("Coefficient", "SE", "Std_Coefficient", "t", "df_error", "p"),
starred = NA,
bolded = NA,
column_formats = NULL,
t_with_df = TRUE,
...
)
## S3 method for class 'glm'
apa_parameters(
fit,
predictor_parameters = c("Parameter", "Coefficient", "SE", "Exp_Coefficient", "t", "z",
"df_error", "p"),
starred = NA,
bolded = NA,
column_formats = NULL,
t_with_df = TRUE,
exponentiate = NULL,
...
)
## S3 method for class 'aov'
apa_parameters(
fit,
predictor_parameters = NULL,
starred = NA,
bolded = NA,
column_formats = NULL,
t_with_df = TRUE,
...
)
## S3 method for class 'aovlist'
apa_parameters(
fit,
predictor_parameters = NULL,
starred = NA,
bolded = NA,
column_formats = NULL,
t_with_df = TRUE,
...
)
## S3 method for class 'afex_aov'
apa_parameters(
fit,
predictor_parameters = NULL,
starred = NA,
bolded = NA,
column_formats = NULL,
t_with_df = TRUE,
...
)
## S3 method for class 'betareg'
apa_parameters(
fit,
predictor_parameters = c("Parameter", "Coefficient", "SE", "Exp_Coefficient", "z", "p"),
starred = NA,
bolded = NA,
column_formats = NULL,
t_with_df = TRUE,
exponentiate = NULL,
component_headings = TRUE,
...
)
## S3 method for class 'clmm'
apa_parameters(
fit,
predictor_parameters = c("Parameter", "Coefficient", "SE", "Exp_Coefficient", "z", "p"),
starred = NA,
bolded = NA,
column_formats = NULL,
t_with_df = TRUE,
exponentiate = NULL,
thresholds = TRUE,
random = TRUE,
effect_headings = TRUE,
random_scale = c("sd", "variance"),
...
)
## S3 method for class 'gam'
apa_parameters(
fit,
predictor_parameters = c("Parameter", "Coefficient", "SE", "Exp_Coefficient", "t", "z",
"df_error", "edf", "F", "Chi2", "p"),
starred = NA,
bolded = NA,
column_formats = NULL,
t_with_df = TRUE,
exponentiate = NULL,
terms = c("all", "parametric", "smooth"),
...
)
## S3 method for class 'bam'
apa_parameters(
fit,
predictor_parameters = c("Parameter", "Coefficient", "SE", "Exp_Coefficient", "t", "z",
"df_error", "edf", "F", "Chi2", "p"),
starred = NA,
bolded = NA,
column_formats = NULL,
t_with_df = TRUE,
exponentiate = NULL,
terms = c("all", "parametric", "smooth"),
...
)
## S3 method for class 'geeglm'
apa_parameters(
fit,
predictor_parameters = c("Parameter", "Coefficient", "SE", "Exp_Coefficient", "z", "p"),
starred = NA,
bolded = NA,
column_formats = NULL,
t_with_df = TRUE,
exponentiate = NULL,
ci = 0.95,
correlation_rows = NULL,
...
)
## S3 method for class 'lavaan'
apa_parameters(
fit,
predictor_parameters = NULL,
starred = NA,
bolded = NA,
column_formats = NULL,
t_with_df = TRUE,
standardize = TRUE,
variances = FALSE,
intercepts = FALSE,
thresholds = FALSE,
ci = 0.95,
groups = c("columns", "rows"),
...
)
## S3 method for class 'rma'
apa_parameters(
fit,
predictor_parameters = c("Parameter", "Coefficient", "SE", "CI", "Exp_Coefficient",
"z", "t", "df_error", "p"),
starred = NA,
bolded = NA,
column_formats = NULL,
t_with_df = TRUE,
studies = NULL,
weights = TRUE,
transform = TRUE,
...
)
## S3 method for class 'mlm'
apa_parameters(
fit,
predictor_parameters = c("Parameter", "Coefficient", "SE", "Std_Coefficient", "t",
"df_error", "p"),
starred = NA,
bolded = NA,
column_formats = NULL,
t_with_df = TRUE,
outcomes = c("rows", "columns"),
...
)
## S3 method for class 'multinom'
apa_parameters(
fit,
predictor_parameters = c("Parameter", "Coefficient", "SE", "Exp_Coefficient", "z", "p"),
starred = NA,
bolded = NA,
column_formats = NULL,
t_with_df = TRUE,
exponentiate = TRUE,
category_headings = TRUE,
...
)
## S3 method for class 'zeroinfl'
apa_parameters(
fit,
predictor_parameters = c("Parameter", "Coefficient", "SE", "Exp_Coefficient", "z", "p"),
starred = NA,
bolded = NA,
column_formats = NULL,
t_with_df = TRUE,
exponentiate = TRUE,
component_headings = TRUE,
...
)
## S3 method for class 'hurdle'
apa_parameters(
fit,
predictor_parameters = c("Parameter", "Coefficient", "SE", "Exp_Coefficient", "z", "p"),
starred = NA,
bolded = NA,
column_formats = NULL,
t_with_df = TRUE,
exponentiate = TRUE,
component_headings = TRUE,
...
)
## S3 method for class 'rq'
apa_parameters(
fit,
predictor_parameters = c("Parameter", "Coefficient", "SE", "t", "df_error", "p"),
starred = NA,
bolded = NA,
column_formats = NULL,
t_with_df = TRUE,
se = c("nid", "iid", "ker", "boot"),
ci = 0.95,
...
)
## S3 method for class 'rqs'
apa_parameters(
fit,
predictor_parameters = c("Parameter", "Coefficient", "SE", "t", "df_error", "p"),
starred = NA,
bolded = NA,
column_formats = NULL,
t_with_df = TRUE,
se = c("nid", "iid", "ker", "boot"),
ci = 0.95,
quantiles = c("columns", "rows"),
...
)
## S3 method for class 'rlm'
apa_parameters(
fit,
predictor_parameters = c("Parameter", "Coefficient", "SE", "t", "df_error", "p"),
starred = NA,
bolded = NA,
column_formats = NULL,
t_with_df = TRUE,
...
)
## S3 method for class 'lmrob'
apa_parameters(
fit,
predictor_parameters = c("Parameter", "Coefficient", "SE", "t", "df_error", "p"),
starred = NA,
bolded = NA,
column_formats = NULL,
t_with_df = TRUE,
...
)
## S3 method for class 'coxph'
apa_parameters(
fit,
predictor_parameters = c("Parameter", "Coefficient", "SE", "Exp_Coefficient", "z", "p"),
starred = NA,
bolded = NA,
column_formats = NULL,
t_with_df = TRUE,
exponentiate = TRUE,
...
)
## S3 method for class 'survreg'
apa_parameters(
fit,
predictor_parameters = c("Parameter", "Coefficient", "SE", "Exp_Coefficient", "z", "p"),
starred = NA,
bolded = NA,
column_formats = NULL,
t_with_df = TRUE,
exponentiate = NULL,
...
)
## S3 method for class 'lm'
apa_parameters(
fit,
predictor_parameters = c("Parameter", "Coefficient", "SE", "Std_Coefficient", "t",
"df_error", "p"),
starred = NA,
bolded = NA,
column_formats = NULL,
t_with_df = TRUE,
...
)
## S3 method for class 'polr'
apa_parameters(
fit,
predictor_parameters = c("Parameter", "Coefficient", "SE", "Exp_Coefficient", "z", "p"),
starred = NA,
bolded = NA,
column_formats = NULL,
t_with_df = TRUE,
exponentiate = NULL,
thresholds = TRUE,
...
)
## S3 method for class 'clm'
apa_parameters(
fit,
predictor_parameters = c("Parameter", "Coefficient", "SE", "Exp_Coefficient", "z", "p"),
starred = NA,
bolded = NA,
column_formats = NULL,
t_with_df = TRUE,
exponentiate = NULL,
thresholds = TRUE,
...
)
## S3 method for class 'merMod'
apa_parameters(
fit,
predictor_parameters = c("Parameter", "Coefficient", "SE", "Exp_Coefficient", "t", "z",
"df_error", "p"),
starred = NA,
bolded = NA,
column_formats = NULL,
t_with_df = TRUE,
exponentiate = NULL,
random = TRUE,
effect_headings = TRUE,
random_scale = c("sd", "variance"),
...
)
## S3 method for class 'glmmTMB'
apa_parameters(
fit,
predictor_parameters = c("Parameter", "Coefficient", "SE", "Exp_Coefficient", "t", "z",
"df_error", "p"),
starred = NA,
bolded = NA,
column_formats = NULL,
t_with_df = TRUE,
exponentiate = NULL,
random = TRUE,
effect_headings = TRUE,
random_scale = c("sd", "variance"),
...
)
## S3 method for class 'lme'
apa_parameters(
fit,
predictor_parameters = c("Parameter", "Coefficient", "SE", "t", "df_error", "p"),
starred = NA,
bolded = NA,
column_formats = NULL,
t_with_df = TRUE,
random = TRUE,
effect_headings = TRUE,
random_scale = c("sd", "variance"),
...
)
## S3 method for class 'list'
apa_parameters(
fit,
predictor_parameters = NULL,
starred = "deltaR2",
bolded = NA,
column_formats = NULL,
t_with_df = TRUE,
performance_parameters = c("R2", "deltaR2"),
performance_layout = c("rows", "columns"),
...
)
Arguments
fit |
a fitted model: |
predictor_parameters |
columns to display, in order, named as in
|
starred |
columns to which significance stars are added (e.g., |
bolded |
columns whose values are bolded when p |
column_formats |
|
t_with_df |
if |
... |
arguments passed to methods. For |
exponentiate |
if |
component_headings |
for models with two components, if |
thresholds |
for ordinal models, if |
random |
for mixed models, if |
effect_headings |
for mixed models, if |
random_scale |
for mixed models, |
terms |
for generalized additive models ( |
ci |
for quantile regression ( |
correlation_rows |
for generalized estimating equations
( |
standardize |
for |
variances, intercepts |
for |
groups |
for multiple-group |
studies |
for meta-analyses ( |
weights |
for the study rows of meta-analyses, if |
transform |
for meta-analyses, if |
outcomes |
for multivariate linear models ( |
category_headings |
for multinomial models, if |
se |
for quantile regression models, the method of computing standard
errors, passed to |
quantiles |
for quantile regression models with several quantiles
( |
performance_parameters |
for lists of models, model comparison metrics passed to |
performance_layout |
for lists of models, where the model comparison metrics go: |
Details
For lists of models in rows (the default layout), each model's statistics follow its parameters, and the first model is tested against a model with only a constant (and the random effects of mixed models). The test row is starred, and the note defines it. The defaults by kind of model are:
| Models | Fit | Test of the change | Also |
lm; glm with an estimated dispersion | R^2^ and \Delta R^2 | F | |
glm with a fixed dispersion (e.g., binomial, Poisson) | pseudo-R^2^ | likelihood ratio \chi^2 | AIC |
polr, clm, multinom, betareg | pseudo-R^2^ | likelihood ratio \chi^2 | AIC |
zeroinfl, hurdle | likelihood ratio \chi^2 | AIC | |
Mixed models (lme4, glmmTMB, nlme, clmm) | marginal and conditional R^2^ | likelihood ratio \chi^2 | AIC |
coxph, survreg | Nagelkerke's R^2^ and C | likelihood ratio \chi^2 | AIC |
lmrob | robust R^2^ and its change | robust Wald \chi^2 | |
rlm | robust residual scale | none | |
rq | R^1^ | none | AIC |
GEE (geeglm) | QIC | Wald \chi^2 of the added terms | |
GAMs (mgcv) | R^2^ and \Delta R^2 | none | AIC |
Lists of different kinds of models get R^2^ and \Delta R^2. Give
performance_parameters to choose the statistics yourself.
For glm objects (including MASS::glm.nb), the test statistic is z for families with a fixed dispersion parameter (binomial, Poisson, negative binomial) and t for families with an estimated dispersion parameter (Gaussian, Gamma, inverse Gaussian, quasi families). Whichever statistic applies is displayed. The exponentiated coefficient column (Exp_Coefficient) is labeled OR for logit links, IRR for log links in count models (Poisson, quasi-Poisson, negative binomial), RR for log links in binomial models, and Exp(B) otherwise.
For aov models (including repeated-measures models with an Error() term) and afex models, apa_parameters() returns the ANOVA table from apa_anova(). predictor_parameters and t_with_df are ignored, and other arguments in ... (e.g., effect_size, type) are passed to apa_anova(). To display regression coefficients instead, refit the model with stats::lm().
For beta regression models (betareg::betareg), which model outcomes
between 0 and 1 (e.g., proportions), the mean model and the precision
model (\phi) are each introduced by a heading row ("Mean model"
and "Precision model"). Coefficients are tested with Wald z tests. With
a logit link for the mean (the default), mean coefficients are log odds of
the mean proportion, and their exponentiated values (shown by default) are
odds ratios, labeled OR. Precision coefficients are not exponentiated.
Higher precision means less variability around the mean. A constant
precision (a model without a | part, as in y ~ x) is shown as one
\phi row with its estimate and standard error, without a test.
apa_note() names the links and gives the number of cases.
For ordinal mixed models (cumulative link mixed models fit with
ordinal::clmm()), the predictors and thresholds are displayed as for
ordinal::clm() models: Wald z tests, cumulative odds ratios (OR) for
logit links, and thresholds (cutpoints) below the predictors, without
tests. The random effects are displayed as for lme4 models, under a
"Random effects" heading (see random, effect_headings, and
random_scale). Models fit with the older ordinal::clmm2() are not
supported.
For generalized additive models fit with mgcv::gam() or mgcv::bam(),
the table has the parametric terms (coefficients, standard errors, and
their t or z tests) and the smooth terms (effective degrees of freedom
and their approximate F or \chi^2 tests), as reported
by summary(), under the headings "Parametric terms" and "Smooth terms".
Smooth terms are labeled by their type and variables (e.g., "s(Age)" or
"te(Longitude, Latitude)"), and smooths of a factor-by variable are labeled
by level (e.g., "s(Age): Group = Treatment"). Coefficients of log and logit
links are exponentiated by default, as for stats::glm() models.
apa_note() names the method used to estimate the smoothing parameters.
For generalized estimating equations fit with geepack::geeglm(),
coefficients are shown as for glm models, with exponentiated
coefficients for logit and log links, and tested with Wald z tests
(z^2^ is geepack's Wald statistic). Standard errors are geepack's
robust (sandwich) estimates, or its jackknife estimates if the model was
fit with them (std.err). The estimated parameters of the working
correlation are shown below the coefficients, with their standard errors
but no tests (correlation_rows; when they are not shown, a single
\alpha is given in the note). apa_note() names the link, the
working correlation, the kind of standard errors, and the numbers of
observations and clusters. Lists of models are compared with Wald tests
of the terms added to the previous model (from geepack's anova()) and
by QIC, because GEE models have no likelihood.
For structural equation models and confirmatory factor analyses fit with lavaan, estimates come from lavaan::standardizedSolution() (standardize = TRUE, default) or lavaan::parameterEstimates() (standardize = FALSE). Each kind of parameter is introduced by a heading row: "Factor loadings" (e.g., Visual \rightarrow x1), "Regressions" (e.g., Speed \leftarrow Visual), "Correlations" (or "Covariances", if unstandardized; e.g., Visual \leftrightarrow Textual), and "Defined parameters" (e.g., indirect effects defined with :=), followed, if requested, by variances, intercepts, and thresholds. The default columns are the estimate, its standard error, and its p-value; "z", "CI", and (with standardize = TRUE) "Coefficient" for unstandardized estimates can be added to predictor_parameters. Unstandardized parameters fixed to set the scale of a factor (e.g., marker loadings fixed at 1) are not tested. Variable names are shown as written in the model, with the first letter capitalized and underscores replaced by spaces.
For multiple-group models (e.g., group = "school"), the groups are shown side by side by default, with one row for each parameter and a column spanner for each group, so that the groups can be compared row by row. With groups = "rows", each group has a heading row, with the kinds of parameters indented below it. A defined parameter that uses the labels of one group is shown with that group. One that combines groups (e.g., the difference between two groups' paths) is shown in the first group's columns, or under an "Across groups" heading. apa_note() gives the size of each group and names the parameters constrained to be equal across groups (group.equal), and any exceptions (group.partial). Standardized estimates of equal parameters can still differ across groups, because standardization uses each group's variances.
For meta-analyses fit with metafor::rma() (random-effects or
equal-effects models, without or with moderators), the table of a model
without moderators has a row for each study, labeled by the study labels
(slab), with its effect size, confidence interval, and percentage of the
total weight, followed by the pooled estimate under a rule. The column of
effect sizes is named by the measure given to metafor::escalc() (e.g.,
g for standardized mean differences, r for correlations, and OR for
odds ratios). apa_note() names the measure and the model (including the
estimator of \tau^2), and gives the test of the pooled
estimate, its prediction interval, and the test of heterogeneity. The
table of a meta-regression has the intercept and moderators, as for other
regression models. apa_performance() gives the heterogeneity statistics.
Multilevel meta-analyses fit with metafor::rma.mv() (e.g., several effect
sizes nested in studies, with random = ~ 1 | study / effect) get the
same tables, with a row for each effect size. apa_note() names the
levels and their numbers of units, and gives each level's variance
component (\sigma^2) and the multilevel I^2
(Cheung, 2014). Random effects with an ~ inner | outer structure (e.g.,
correlated outcomes within studies) are not yet supported.
For multivariate linear models, fit with stats::lm() and several outcomes
(lm(cbind(y1, y2) ~ x), class mlm), each outcome's coefficients are
shown as for an lm model, under a heading row for each outcome (or side
by side, with outcomes = "columns"). The coefficients and their tests
are those of a separate regression of each outcome on the same
predictors, so they do not take the correlations among the outcomes into
account. For multivariate tests of each predictor, use apa_anova().
Lists of multivariate models are not supported yet.
For multinomial logistic regression models (nnet::multinom), each outcome
category except the reference category (the first level of the response)
has its own block of coefficients, introduced by a heading row such as
"Part time vs. Not working". Coefficients are log odds of the category
relative to the reference category, tested with Wald z tests, and their
exponentiated values (shown by default) are odds ratios relative to the
reference category (sometimes called relative risk ratios), labeled OR.
To compare the categories with a different reference, relevel the response
(e.g., with stats::relevel()) before fitting the model. apa_note() names
the reference category.
For zero-inflated and hurdle count models fit with pscl::zeroinfl() and
pscl::hurdle(), the count model and the zero model are each introduced by
a heading row ("Count model" and "Zero-inflation model" or "Zero hurdle
model"); with component_headings = FALSE, the zero model's coefficients
are labeled "Zero-inflation: " or "Zero hurdle: " instead. Coefficients are tested with Wald z tests. Only the count model's
coefficients are exponentiated (by default), giving incidence rate ratios
(IRR), because the zero model has a different link and meaning. In a
zero-inflated model, the zero model predicts excess zeros (zeros not
produced by the count model); in a hurdle model, it predicts whether the
count is greater than zero. apa_note() says which, names the count
distribution, and gives the negative binomial dispersion parameter
(\theta).
For quantile regression models (quantreg::rq), coefficients are the
change in a quantile of the outcome (e.g., the median, with tau = .5)
per unit of the predictor, tested with t tests of the coefficient
divided by its standard error (see se). apa_note() names the quantile
and the kind of standard errors. Models with several quantiles show the
estimates of each quantile side by side (see quantiles).
For robust regression models (MASS::rlm and robustbase::lmrob),
coefficients are tested with t tests, as in linear regression, but
cases with large residuals get less weight. Standardized coefficients are
not shown by default, because standardizing with the ordinary standard
deviations does not match a robust fit. apa_note() names the estimator
and its weight function (e.g., MM-estimation with bisquare weights), says
how the standard errors were computed, and gives N and the number of
cases whose weights are below .10, which have almost no influence on the
estimates. For rlm, the p-values are computed by the parameters
package, because MASS gives none.
For Cox proportional hazards models (survival::coxph), coefficients are
log hazard ratios, tested with Wald z tests, and their exponentiated
values (shown by default) are hazard ratios, labeled HR. A hazard ratio
above 1 means that the event happens sooner (at a higher rate) as the
predictor increases. The model has no intercept. apa_note() names the
model and gives the number of cases and of events.
For parametric survival models (survival::survreg), which are
accelerated failure time models for distributions of log time (e.g., the
default Weibull, exponential, log-normal, and log-logistic), coefficients
are changes in log survival time, tested with Wald z tests, and their
exponentiated values (shown by default) are time ratios, labeled TR. A
time ratio above 1 means that the event happens later as the predictor
increases, the opposite of a hazard ratio above 1. The constant and the
log of the scale parameter, Log(scale), are not exponentiated. The scale
is tested only for Weibull models, where a scale of 1 is the exponential
model. apa_note() names the distribution and gives the number of cases
and of events.
For ordinal regression models (MASS::polr and ordinal::clm), coefficients are tested with Wald z tests. (parameters reports t for polr, but the test is asymptotically normal, and clm reports z for the same model.) With a logit link, exponentiated coefficients are cumulative odds ratios, labeled OR. Threshold rows show only the estimate, its standard error, and its confidence interval, because their exponentiated values are not odds ratios, and testing whether a threshold equals 0 is not meaningful. Confidence intervals ("CI", "Exp_CI") are Wald z intervals, consistent with the z tests.
For mixed models fit with lme4 (lmer and glmer), fixed effects are displayed as for lm and glm models. For linear mixed models, t tests and confidence intervals use Kenward-Roger degrees of freedom by default (ci_method = "kenward", which requires the pbkrtest package); pass another ci_method (e.g., "satterthwaite", which requires lmerTest, or "wald") to change this. When the degrees of freedom differ across fixed effects, they are shown in a df column rather than in the t column header. Random-effect rows show only the estimated standard deviation (SD) or correlation (r), or with random_scale = "variance", the variance (Var) or covariance (Cov), grouped by cluster (grouping factor) under a subheading for each cluster, with nested clusters named, e.g., "Classroom in School". The fixed and random effects are introduced by heading rows (effect_headings = TRUE). The random-effects heading names the statistic of the SD or variance rows (e.g., "Random effects (SD)"), and correlation or covariance rows name their own (e.g., "r (Constant, Days)"). apa_note() defines the symbols.
For mixed models fit with glmmTMB::glmmTMB(), fixed effects are tested with z tests, and random effects are displayed as for lme4 models. Coefficients of log and logit links are exponentiated by default (e.g., IRR for Poisson and negative binomial models). When the model has a zero-inflation part (ziformula) or a dispersion part (dispformula), each part is introduced by a heading row ("Conditional model", "Zero-inflation model", or "Dispersion model"), and only the conditional model's coefficients are exponentiated. A dispersion parameter that is not modeled (i.e., without a dispformula) is not displayed.
For linear mixed models fit with nlme::lme(), fixed effects are tested with t tests whose degrees of freedom are computed by nlme from the grouping levels at which each effect varies, and random effects are displayed as for lme4 models. Parameters of residual correlation structures (correlation, e.g., nlme::corAR1()) and variance functions (weights, e.g., nlme::varIdent()) are displayed below the residual SD, and apa_note() names the structures.
Value
apa7_tbl (tibble)
References
Ferrari, S. L. P., & Cribari-Neto, F. (2004). Beta regression for modelling rates and proportions. Journal of Applied Statistics, 31(7), 799–815. doi:10.1080/0266476042000214501
Smithson, M., & Verkuilen, J. (2006). A better lemon squeezer? Maximum-likelihood regression with beta-distributed dependent variables. Psychological Methods, 11(1), 54–71. doi:10.1037/1082-989X.11.1.54
Halekoh, U., Højsgaard, S., & Yan, J. (2006). The R package geepack for generalized estimating equations. Journal of Statistical Software, 15(2). doi:10.18637/jss.v015.i02
Liang, K.-Y., & Zeger, S. L. (1986). Longitudinal data analysis using generalized linear models. Biometrika, 73(1), 13–22. doi:10.1093/biomet/73.1.13
Pan, W. (2001). Akaike's information criterion in generalized estimating equations. Biometrics, 57(1), 120–125. doi:10.1111/j.0006-341X.2001.00120.x
Cheung, M. W.-L. (2014). Modeling dependent effect sizes with three-level meta-analyses: A structural equation modeling approach. Psychological Methods, 19(2), 211–229. doi:10.1037/a0032968
DerSimonian, R., & Laird, N. (1986). Meta-analysis in clinical trials. Controlled Clinical Trials, 7(3), 177–188. doi:10.1016/0197-2456(86)90046-2
Knapp, G., & Hartung, J. (2003). Improved tests for a random effects meta-regression with a single covariate. Statistics in Medicine, 22(17), 2693–2710. doi:10.1002/sim.1482
Hendricks, W., & Koenker, R. (1992). Hierarchical spline models for conditional quantiles and the demand for electricity. Journal of the American Statistical Association, 87(417), 58–68. doi:10.1080/01621459.1992.10475175
Koenker, R., & Bassett, G. (1978). Regression quantiles. Econometrica, 46(1), 33–50. doi:10.2307/1913643
Koenker, R., & Machado, J. A. F. (1999). Goodness of fit and related inference processes for quantile regression. Journal of the American Statistical Association, 94(448), 1296–1310. doi:10.1080/01621459.1999.10473882
Huber, P. J. (1964). Robust estimation of a location parameter. The Annals of Mathematical Statistics, 35(1), 73–101. doi:10.1214/aoms/1177703732
Renaud, O., & Victoria-Feser, M.-P. (2010). A robust coefficient of determination for regression. Journal of Statistical Planning and Inference, 140(7), 1852–1862. doi:10.1016/j.jspi.2010.01.008
Yohai, V. J. (1987). High breakdown-point and high efficiency robust estimates for regression. The Annals of Statistics, 15(2), 642–656. doi:10.1214/aos/1176350366
Cox, D. R. (1972). Regression models and life-tables. Journal of the Royal Statistical Society: Series B (Methodological), 34(2), 187–202. doi:10.1111/j.2517-6161.1972.tb00899.x
Harrell, F. E., Califf, R. M., Pryor, D. B., Lee, K. L., & Rosati, R. A. (1982). Evaluating the yield of medical tests. JAMA, 247(18), 2543–2546. doi:10.1001/jama.1982.03320430047030
Wei, L. J. (1992). The accelerated failure time model: A useful alternative to the Cox regression model in survival analysis. Statistics in Medicine, 11(14–15), 1871–1879. doi:10.1002/sim.4780111409
Examples
lm(mpg ~ cyl + wt, data = mtcars) |>
apa_parameters() |>
apa_flextable()
# Confidence intervals with robust (HC3) standard errors
if (requireNamespace("sandwich", quietly = TRUE)) {
lm(mpg ~ cyl + wt, data = mtcars) |>
apa_parameters(
predictor_parameters = c("Parameter", "Coefficient", "SE", "CI", "t", "df_error", "p"),
vcov = "HC3"
) |>
apa_flextable()
}
# Hierarchical regression: a list of models, with R-squared and its
# change in rows below each model's parameters
models <- list(
`Model 1` = lm(mpg ~ cyl, data = mtcars),
`Model 2` = lm(mpg ~ cyl + wt, data = mtcars)
)
apa_parameters(models)
# The same statistics in columns
apa_parameters(models, performance_layout = "columns")
# Logistic regression, with odds ratios
glm(am ~ wt + hp, data = mtcars, family = binomial) |>
apa_parameters()
if (requireNamespace("betareg", quietly = TRUE)) {
data("ReadingSkills", package = "betareg")
d <- ReadingSkills
d$dyslexia <- factor(d$dyslexia, levels = c("no", "yes"))
# Reading accuracy, with the precision depending on dyslexia and IQ
betareg::betareg(accuracy ~ dyslexia * iq | dyslexia + iq, data = d) |>
apa_parameters()
}
if (requireNamespace("ordinal", quietly = TRUE)) {
# Bitterness ratings of wine, with judges as a random factor
data("wine", package = "ordinal")
ordinal::clmm(rating ~ temp + contact + (1 | judge), data = wine) |>
apa_parameters()
}
if (requireNamespace("mgcv", quietly = TRUE)) {
mgcv::gam(mpg ~ am + s(hp, k = 5) + s(wt, k = 5), data = mtcars,
method = "REML") |>
apa_parameters()
}
# Generalized estimating equations
if (requireNamespace("geepack", quietly = TRUE)) {
data(ohio, package = "geepack")
fit_gee <- geepack::geeglm(
resp ~ age + smoke,
id = id,
data = ohio,
family = binomial,
corstr = "exchangeable"
)
apa_parameters(fit_gee)
}
if (requireNamespace("lavaan", quietly = TRUE)) {
model <- "visual =~ x1 + x2 + x3
textual =~ x4 + x5 + x6
speed =~ x7 + x8 + x9
speed ~ visual + textual"
lavaan::sem(model, data = lavaan::HolzingerSwineford1939) |>
apa_parameters()
# Multiple groups, side by side
lavaan::cfa(
"visual =~ x1 + x2 + x3",
data = lavaan::HolzingerSwineford1939,
group = "school",
group.equal = "loadings"
) |>
apa_parameters()
}
if (requireNamespace("metafor", quietly = TRUE) &&
requireNamespace("metadat", quietly = TRUE)) {
d_bcg <- metafor::escalc(
measure = "RR",
ai = tpos, bi = tneg, ci = cpos, di = cneg,
data = metadat::dat.bcg,
slab = paste(author, year)
)
fit_meta <- metafor::rma(yi, vi, data = d_bcg)
apa_parameters(fit_meta)
apa_performance(fit_meta)
# Meta-regression
metafor::rma(yi, vi, mods = ~ ablat, data = d_bcg) |>
apa_parameters()
}
# Multivariate regression: the coefficients of each outcome
fit_mlm <- lm(cbind(mpg, qsec) ~ wt + hp, data = mtcars)
apa_parameters(fit_mlm)
apa_parameters(fit_mlm, outcomes = "columns")
if (requireNamespace("nnet", quietly = TRUE) &&
requireNamespace("carData", quietly = TRUE)) {
d <- carData::Womenlf
d$partic <- relevel(d$partic, ref = "not.work")
nnet::multinom(partic ~ hincome + children, data = d, trace = FALSE) |>
apa_parameters()
}
if (requireNamespace("pscl", quietly = TRUE)) {
data("bioChemists", package = "pscl")
pscl::zeroinfl(art ~ fem + kid5 + ment | ment,
data = bioChemists, dist = "negbin") |>
apa_parameters()
}
if (requireNamespace("quantreg", quietly = TRUE) &&
requireNamespace("psych", quietly = TRUE)) {
d <- psych::sat.act
d$female <- as.integer(d$gender == 2)
# ACT scores at the 25th, 50th, and 75th percentiles
quantreg::rq(ACT ~ education + female, tau = c(.25, .5, .75), data = d) |>
suppressWarnings() |>
apa_parameters()
}
if (requireNamespace("robustbase", quietly = TRUE) &&
requireNamespace("carData", quietly = TRUE)) {
# Reported weight by measured weight; one measured weight is a data
# entry error (weight and height swapped)
d <- carData::Davis
robustbase::lmrob(repwt ~ weight * sex, data = d) |>
apa_parameters()
}
if (requireNamespace("survival", quietly = TRUE) &&
requireNamespace("carData", quietly = TRUE)) {
# Time to rearrest after release from prison
survival::coxph(
survival::Surv(week, arrest) ~ fin + age + prio,
data = carData::Rossi
) |>
apa_parameters()
}
if (requireNamespace("MASS", quietly = TRUE) &&
requireNamespace("carData", quietly = TRUE)) {
MASS::polr(poverty ~ gender + age, data = carData::WVS, Hess = TRUE) |>
apa_parameters()
}
if (requireNamespace("lme4", quietly = TRUE) &&
requireNamespace("pbkrtest", quietly = TRUE)) {
lme4::lmer(Reaction ~ Days + (Days | Subject), data = lme4::sleepstudy) |>
apa_parameters()
}
if (requireNamespace("glmmTMB", quietly = TRUE)) {
data(Salamanders, package = "glmmTMB")
glmmTMB::glmmTMB(
count ~ mined + (1 | site),
ziformula = ~ mined,
family = poisson,
data = Salamanders
) |>
apa_parameters()
}
if (requireNamespace("nlme", quietly = TRUE)) {
nlme::lme(
distance ~ age + Sex,
random = ~ 1 | Subject,
correlation = nlme::corAR1(),
data = nlme::Orthodont
) |>
apa_parameters()
}
format model performance metrics in APA style
Description
format model performance metrics in APA style
Fit indices of lavaan models
Usage
apa_performance(fit, metrics = c("R2", "Sigma"), column_formats = NULL)
## S3 method for class 'betareg'
apa_performance(fit, metrics = c("R2", "AIC"), column_formats = NULL)
## S3 method for class 'clmm'
apa_performance(
fit,
metrics = c("R2_marginal", "R2_conditional", "AIC"),
column_formats = NULL
)
## S3 method for class 'gam'
apa_performance(
fit,
metrics = c("R2_adjusted", "Deviance_explained", "AIC"),
column_formats = NULL
)
## S3 method for class 'bam'
apa_performance(
fit,
metrics = c("R2_adjusted", "Deviance_explained", "AIC"),
column_formats = NULL
)
## S3 method for class 'geeglm'
apa_performance(fit, metrics = c("QIC", "QICu"), column_formats = NULL)
## S3 method for class 'lavaan'
apa_performance(
fit,
metrics = c("Chi2", "Chi2_df", "p_Chi2", "CFI", "TLI", "RMSEA", "RMSEA_CI", "SRMR"),
column_formats = NULL
)
## S3 method for class 'rma'
apa_performance(fit, metrics = NULL, column_formats = NULL)
## S3 method for class 'mlm'
apa_performance(
fit,
metrics = c("R2", "R2_adjusted", "Sigma"),
column_formats = NULL
)
## S3 method for class 'multinom'
apa_performance(fit, metrics = c("R2", "AIC"), column_formats = NULL)
## S3 method for class 'zeroinfl'
apa_performance(fit, metrics = c("R2", "AIC"), column_formats = NULL)
## S3 method for class 'hurdle'
apa_performance(fit, metrics = c("R2", "AIC"), column_formats = NULL)
## S3 method for class 'rq'
apa_performance(fit, metrics = c("R1", "AIC"), column_formats = NULL)
## S3 method for class 'rqs'
apa_performance(fit, metrics = c("R1", "AIC"), column_formats = NULL)
## S3 method for class 'lmrob'
apa_performance(fit, metrics = c("R2", "Sigma_robust"), column_formats = NULL)
## S3 method for class 'rlm'
apa_performance(fit, metrics = "Sigma_robust", column_formats = NULL)
## S3 method for class 'coxph'
apa_performance(
fit,
metrics = c("R2", "Concordance", "AIC"),
column_formats = NULL
)
## S3 method for class 'survreg'
apa_performance(
fit,
metrics = c("R2", "Concordance", "AIC"),
column_formats = NULL
)
## S3 method for class 'lm'
apa_performance(fit, metrics = c("R2", "Sigma"), column_formats = NULL)
## S3 method for class 'glm'
apa_performance(fit, metrics = c("R2", "AIC"), column_formats = NULL)
## S3 method for class 'polr'
apa_performance(fit, metrics = c("R2", "AIC"), column_formats = NULL)
## S3 method for class 'clm'
apa_performance(fit, metrics = c("R2", "AIC"), column_formats = NULL)
## S3 method for class 'merMod'
apa_performance(
fit,
metrics = c("R2_marginal", "R2_conditional", "ICC"),
column_formats = NULL
)
## S3 method for class 'glmmTMB'
apa_performance(
fit,
metrics = c("R2_marginal", "R2_conditional", "ICC"),
column_formats = NULL
)
## S3 method for class 'lme'
apa_performance(
fit,
metrics = c("R2_marginal", "R2_conditional", "ICC"),
column_formats = NULL
)
## S3 method for class 'list'
apa_performance(fit, metrics = NULL, column_formats = NULL)
Arguments
fit |
a fitted model of any class that |
metrics |
fit statistics to display, named as in
|
column_formats |
column_formats object to format columns. If NULL, the default column_formats is used. |
Details
For beta regression models (betareg::betareg), R2 is the pseudo-R^2^
of Ferrari and Cribari-Neto (2004): the squared correlation of the linear
predictor and the link-transformed outcome. The default metrics are R2
and AIC. Nested models are compared with likelihood ratio tests in
apa_performance_comparison().
For ordinal mixed models (ordinal::clmm), the default metrics are the
marginal and conditional R^2^ (R2_marginal and R2_conditional) and
AIC. Nested models are compared with likelihood ratio tests in
apa_performance_comparison().
For generalized additive models (mgcv::gam and mgcv::bam), the
metrics are the adjusted R^2^ ("R2_adjusted"), the percentage of the
deviance explained ("Deviance_explained"), the number of observations
("n"), "AIC", and "BIC", as reported by summary(). The defaults are
"R2_adjusted", "Deviance_explained", and "AIC".
For generalized estimating equations (geepack::geeglm), the default
metrics are QIC and QICu (Pan, 2001), from geepack::QIC(); "all"
adds CIC. GEE models have no likelihood, so there is no AIC or
likelihood-based R^2^.
For structural equation models and confirmatory factor analyses fit with
lavaan (e.g., lavaan::cfa() or lavaan::sem()), the default metrics
are the model \chi^2 test ("Chi2", "Chi2_df", "p_Chi2"), the
comparative fit index ("CFI"), the Tucker-Lewis index ("TLI"), the root
mean square error of approximation with its confidence interval
("RMSEA", "RMSEA_CI"), and the standardized root mean square residual
("SRMR"). "AIC" and "BIC" are also available, and "all" selects
every metric. Values come from lavaan::fitMeasures(). When the model was
fit with a robust estimator (e.g., estimator = "MLR" or "WLSMV"), the
scaled \chi^2 test and the robust (or, if unavailable, scaled) CFI,
TLI, and RMSEA are displayed. apa_note() gives the sample size, the
estimator, and how missing data were handled, and defines the
abbreviations.
For meta-analyses (metafor::rma()), the metrics are the number of
studies ("k"), the test of residual heterogeneity ("QE" and "p_QE",
with its df in the header), \tau^2 ("tau2") and
\tau ("tau"), I^2 ("I2"), H^2
("H2"), confidence intervals of \tau^2 and I^2
("tau2_CI" and "I2_CI", from stats::confint()), and, for
meta-regressions, the omnibus test of the moderators ("QM" and "p_QM")
and the proportion of heterogeneity they explain ("R2"). The defaults are
"k", "QE", "p_QE", "tau2", and "I2", plus "QM", "p_QM", and
"R2" for meta-regressions. Equal-effects models have no
\tau^2.
For multilevel meta-analyses (metafor::rma.mv()), "k" is the number of
effect sizes, and the variance components are reported for each level:
\sigma^2 ("sigma2"), \sigma ("sigma"), and
their confidence intervals ("sigma2_CI"), with the level as a subscript.
"I2" is the multilevel I^2 for all levels together, and
"I2_levels" gives it for each level (Cheung, 2014). The defaults are
"k", "QE", "p_QE", "sigma2", and "I2", plus "QM" and "p_QM"
for meta-regressions.
For multivariate linear models (class mlm), each outcome gets a row
(labeled in an Outcome column) with its R^2^, adjusted R^2^, and
residual SD (Sigma), computed from stats::summary.lm() for each
outcome. "all" adds the overall F test of each outcome's regression.
For multinomial logistic regression models (nnet::multinom), R2 is
McFadden's pseudo-R^2^, and the default metrics are R2 and AIC.
For zero-inflated and hurdle models (pscl::zeroinfl and pscl::hurdle),
R2 is computed by performance::r2_zeroinflated(), and the default
metrics are R2 and AIC.
For quantile regression models (quantreg::rq), R1 is the
Koenker-Machado goodness of fit, R^1^: the proportional reduction in the
sum of weighted absolute residuals from the model with only an intercept
at the same quantile. It is the quantile regression counterpart of
R^2^, and it is usually smaller. The default metrics are R1 and AIC.
Models with several quantiles get a row for each quantile. Lists of models
are compared in apa_performance_comparison() by R^1^ and AIC,
without tests.
For robust regression models fit with robustbase::lmrob, R2 is the
robust R^2^ of Renaud and Victoria-Feser (2010), and Sigma_robust is
the robust residual scale. For models fit with MASS::rlm, which have no
R^2^, the default metric is the robust residual scale. Nested lmrob
models are compared with robust Wald tests in
apa_performance_comparison(), and rlm models without tests.
For Cox proportional hazards models (survival::coxph), R2 is
Nagelkerke's pseudo-R^2^ and Concordance is the concordance index
(Harrell's C): the proportion of pairs of cases in which the case with
the higher predicted risk had the event sooner. The default metrics are
R2, Concordance, and AIC. Nested models are compared with likelihood
ratio tests in apa_performance_comparison().
For parametric survival models (survival::survreg), R2 is
Nagelkerke's pseudo-R^2^ and Concordance is the concordance index
(Harrell's C), as for Cox models. The default metrics are R2,
Concordance, and AIC, and nested models are compared with likelihood
ratio tests in apa_performance_comparison().
For glm objects, R2 is the pseudo-R^2^ that performance::r2() selects for the model family (e.g., Tjur's R^2^ for logistic regression and Nagelkerke's R^2^ for count models). The header names the pseudo-R^2^ that was used. Because the residual standard deviation is not meaningful for most GLMs, the default metrics are R2 and AIC.
For mixed models (lme4::lmer, lme4::glmer, glmmTMB::glmmTMB, and nlme::lme), the default metrics are the marginal R^2^ (variance explained by the fixed effects), the conditional R^2^ (fixed and random effects), and the intraclass correlation (ICC), as computed by performance::model_performance().
For a list of models, each model's metrics are displayed in a row, labeled in a Model column by the list's names (or "Model 1", "Model 2", ... for unnamed elements). If metrics is NULL (default), each model's default metrics are used.
Value
apa7_tbl (tibble)
References
McFadden, D. (1974). Conditional logit analysis of qualitative choice behavior. In P. Zarembka (Ed.), Frontiers in econometrics (pp. 105–142). Academic Press.
Nagelkerke, N. J. D. (1991). A note on a general definition of the coefficient of determination. Biometrika, 78(3), 691–692. doi:10.1093/biomet/78.3.691
Nakagawa, S., & Schielzeth, H. (2013). A general and simple method for
obtaining R^2 from generalized linear mixed-effects models. Methods
in Ecology and Evolution, 4(2), 133–142.
doi:10.1111/j.2041-210x.2012.00261.x
Satorra, A., & Bentler, P. M. (1994). Corrections to test statistics and standard errors in covariance structure analysis. In A. von Eye & C. C. Clogg (Eds.), Latent variables analysis: Applications for developmental research (pp. 399–419). Sage.
Tjur, T. (2009). Coefficients of determination in logistic regression models—A new proposal: The coefficient of discrimination. The American Statistician, 63(4), 366–372. doi:10.1198/tast.2009.08210
Yuan, K.-H., & Bentler, P. M. (2000). Three likelihood-based methods for mean and covariance structure analysis with nonnormal missing data. Sociological Methodology, 30(1), 165–200. doi:10.1111/0081-1750.00078
Examples
lm(mpg ~ cyl + wt, data = mtcars) |>
apa_performance() |>
apa_flextable()
if (requireNamespace("lavaan", quietly = TRUE)) {
model <- "visual =~ x1 + x2 + x3
textual =~ x4 + x5 + x6
speed =~ x7 + x8 + x9"
fit_cfa <- lavaan::cfa(model, data = lavaan::HolzingerSwineford1939)
apa_performance(fit_cfa)
}
list(
`Cylinders` = lm(mpg ~ cyl, data = mtcars),
`Cylinders and weight` = lm(mpg ~ cyl + wt, data = mtcars)
) |>
apa_performance()
format model comparison metrics in APA style
Description
format model comparison metrics in APA style
Usage
apa_performance_comparison(
...,
metrics = NULL,
starred = NA,
column_formats = NULL
)
Arguments
... |
model fit objects, or a list of them. Models are labeled by the list's names (or the argument names), and "Model 1", "Model 2", ... for unnamed models. |
metrics |
performance metrics. If |
starred |
columns to which significance stars are added (e.g., |
column_formats |
column_formats object to format columns. If NULL, the default column_formats is used. |
Details
Nested models are compared with F tests (performance::test_wald()) unless every model is a GLM with a fixed dispersion parameter, in which case likelihood ratio tests (performance::test_likelihoodratio()) are used. For GLMs, R2 is the pseudo-R^2^ that performance::r2() selects for the model family, and the header names it (e.g., R^2^~Tjur~).
Robust regression models fit with robustbase::lmrob are compared with robust Wald tests (robustbase::anova.lmrob()), and R2 is the robust R^2^; models fit with MASS::rlm are compared by the robust residual scale, without tests.
Cox proportional hazards models (survival::coxph) are compared with likelihood ratio tests, and R2 is Nagelkerke's pseudo-R^2^. So are beta regression models (betareg::betareg), with Ferrari and Cribari-Neto's pseudo-R^2^. Quantile regression models (quantreg::rq) are compared by the Koenker-Machado R^1^ and AIC, without tests.
Parametric survival models (survival::survreg) are compared like Cox models. Generalized estimating equations (geepack::geeglm) have no likelihood, so they are compared by QIC and Wald tests of the added terms (from geepack's anova()).
Mixed models (lme4::lmer, lme4::glmer, glmmTMB::glmmTMB, nlme::lme, and ordinal::clmm) are compared with likelihood ratio tests. R2 is the marginal R^2^ (variance explained by the fixed effects), and by default the conditional R^2^ (fixed and random effects) and its change (R2_conditional, deltaR2_conditional) are shown too, because adding random effects changes the conditional but not the marginal R^2^.
Nested lavaan models (e.g., the configural, metric, and scalar models of a measurement invariance analysis) are compared each with the one before it, so they should be listed from the least to the most constrained. Each row shows the fit of the model (any of the metrics of apa_performance.lavaan()), followed, under a "Change from previous model" spanner, by the chi-square difference test from lavaan::lavTestLRT() ("deltaChi2", "deltaChi2_df", "p_deltaChi2") and the changes in fit indices ("deltaCFI", "deltaTLI", "deltaRMSEA", "deltaSRMR"), shown with three decimals. The default metrics are "Chi2", "Chi2_df", "CFI", "RMSEA", "RMSEA_CI", "SRMR", "deltaChi2", "deltaChi2_df", "p_deltaChi2", "deltaCFI", and "deltaRMSEA". With a robust estimator (e.g., MLR or WLSMV), the difference test is scaled (e.g., the Satorra-Bentler scaled difference test), and the changes in fit indices are computed from their robust versions. apa_note() names the difference test. starred is ignored for lavaan models.
Value
apa7_tbl (tibble)
References
Satorra, A. (2000). Scaled and adjusted restricted tests in multi-sample analysis of moment structures. In R. D. H. Heijmans, D. S. G. Pollock, & A. Satorra (Eds.), Innovations in multivariate statistical analysis (pp. 233–247). Kluwer Academic Publishers. doi:10.1007/978-1-4615-4603-0_17
Satorra, A., & Bentler, P. M. (2001). A scaled difference chi-square test statistic for moment structure analysis. Psychometrika, 66(4), 507–514. doi:10.1007/BF02296192
Satorra, A., & Bentler, P. M. (2010). Ensuring positiveness of the scaled difference chi-square test statistic. Psychometrika, 75(2), 243–248. doi:10.1007/s11336-009-9135-y
Examples
m1 <- lm(mpg ~ cyl, data = mtcars)
m2 <- lm(mpg ~ cyl + wt, data = mtcars)
apa_performance_comparison(list(Cylinders = m1, `Cylinders and weight` = m2)) |>
apa_flextable()
# Measurement invariance across schools
if (requireNamespace("lavaan", quietly = TRUE)) {
model <- "visual =~ x1 + x2 + x3
textual =~ x4 + x5 + x6
speed =~ x7 + x8 + x9"
hs <- lavaan::HolzingerSwineford1939
apa_performance_comparison(
Configural = lavaan::cfa(model, data = hs, group = "school"),
Metric = lavaan::cfa(model, data = hs, group = "school",
group.equal = "loadings"),
Scalar = lavaan::cfa(model, data = hs, group = "school",
group.equal = c("loadings", "intercepts"))
)
}
Publication bias table for a meta-analysis
Description
Makes an APA-style table of tests and corrections for publication bias
(small-study effects) in a meta-analysis fit with metafor::rma(), as
computed by metafor.
Usage
apa_publication_bias(
fit,
methods = c("egger", "rank", "trimfill"),
transform = TRUE
)
Arguments
fit |
a meta-analysis fit with |
methods |
methods to display, in order: any of |
transform |
if |
Details
The methods (rows) are:
-
"egger": Egger's regression test (metafor::regtest()), a meta-regression of the effect sizes on their standard errors. The test statistic is the test of the standard error's coefficient, and the adjusted estimate is the limit estimate (the predicted effect as the standard error approaches zero, as in PET). -
"rank": Begg and Mazumdar's rank correlation test (metafor::ranktest()), Kendall's\taubetween the standardized effect sizes and their variances. -
"trimfill": the trim-and-fill method (metafor::trimfill()), which imputes the studies (k_0) that seem to be missing from one side of the funnel plot and gives the pooled estimate with them included. -
"fsn": the fail-safe N (metafor::fsn()), the number of additional studies with an average effect of zero that would make the pooled estimate nonsignificant. It is widely criticized and is not shown by default.
Adjusted estimates are shown on the same scale as in apa_parameters()
(e.g., risk ratios are exponentiated, and Fisher's z values are
converted back to correlations), and apa_note() gives the unadjusted
pooled estimate for comparison and describes each method.
These methods are available for models fit with metafor::rma(), not for
multilevel models (metafor::rma.mv()), for which the standard error (or
sampling variance) can be added as a moderator instead.
Value
apa7_tbl (tibble)
References
Begg, C. B., & Mazumdar, M. (1994). Operating characteristics of a rank correlation test for publication bias. Biometrics, 50(4), 1088–1101. doi:10.2307/2533446
Duval, S., & Tweedie, R. (2000). Trim and fill: A simple funnel-plot-based method of testing and adjusting for publication bias in meta-analysis. Biometrics, 56(2), 455–463. doi:10.1111/j.0006-341X.2000.00455.x
Egger, M., Davey Smith, G., Schneider, M., & Minder, C. (1997). Bias in meta-analysis detected by a simple, graphical test. BMJ, 315(7109), 629–634. doi:10.1136/bmj.315.7109.629
Examples
if (requireNamespace("metafor", quietly = TRUE) &&
requireNamespace("metadat", quietly = TRUE)) {
d_bcg <- metafor::escalc(
measure = "RR",
ai = tpos, bi = tneg, ci = cpos, di = cneg,
data = metadat::dat.bcg
)
fit_meta <- metafor::rma(yi, vi, data = d_bcg)
apa_publication_bias(fit_meta)
}
Reliability and item analysis table
Description
Makes an APA-style table of the reliability of one or more scales: for each
item, its mean, standard deviation, corrected item-total correlation, and
Cronbach's \alpha if the item were deleted, followed for each
scale by the scale score's mean and standard deviation, Cronbach's
\alpha with its confidence interval, McDonald's
\omega_{\text{total}}, and the mean inter-item
correlation.
Usage
apa_reliability(
data,
scales = NULL,
reverse = NULL,
item_range = NULL,
level = c("items", "scales"),
omega = TRUE,
ci = 0.95,
score = c("mean", "sum"),
flag = NULL,
format_variable_names = TRUE,
digits = 2
)
Arguments
data |
data frame of item responses |
scales |
named list of the items of each scale, given as unquoted or
quoted names or tidyselect helpers (e.g., |
reverse |
items to reverse-score before the analysis, selected like
the items in |
item_range |
lowest and highest possible responses, used to reverse
items. If |
level |
|
omega |
if |
ci |
confidence level of the interval of |
score |
|
flag |
|
format_variable_names |
if |
digits |
number of decimal places (unaffected by
|
Details
The corrected item-total correlation (r~it~) is the item's correlation
with the sum of the other items in its scale. Items with low values (often,
below .30) discriminate poorly. \alpha if deleted is the
scale's \alpha without the item; values above the scale's
\alpha mean that the item lowers reliability.
Cronbach's \alpha, the item statistics, and the mean
inter-item correlation come from psych::alpha(). The confidence interval
of \alpha is Feldt's. \omega_{\text{total}}
is computed from a one-factor model (psych::fa(), minimum residual):
(\sum\lambda)^2 / ((\sum\lambda)^2 + \sum\psi).
Each scale uses the respondents who answered all of its items, and the
note gives their number. Scale scores are the means of the items (or their
sums, with score = "sum").
When all items of a scale are scored 0 and 1 (e.g., incorrect and correct
answers), M is the item's difficulty (the proportion of 1s), r~it~ is
the corrected point-biserial correlation, and \alpha equals
KR-20. The note says so.
Value
apa7_tbl (tibble)
References
Feldt, L. S., Woodruff, D. J., & Salih, F. A. (1987). Statistical inference for coefficient alpha. Applied Psychological Measurement, 11(1), 93–103. doi:10.1177/014662168701100107
McDonald, R. P. (1999). Test theory: A unified treatment. Lawrence Erlbaum. doi:10.4324/9781410601087
Examples
d <- psych::bfi
apa_reliability(
d,
scales = list(
Agreeableness = paste0("A", 1:5),
Conscientiousness = paste0("C", 1:5)
),
reverse = c("A1", "C4", "C5"),
item_range = c(1, 6)
)
# One row per scale, with items selected by tidyselect helpers
apa_reliability(
d,
scales = list(
Agreeableness = A1:A5,
Conscientiousness = starts_with("C")
),
reverse = c(A1, C4, C5),
item_range = c(1, 6),
level = "scales"
)
Style flextable::flextable object according to APA style
Description
apa_style() applies the fonts, rules, spacing, and alignment of an APA-style
table to a flextable and converts markdown in its cells. apa_flextable()
calls it, so it is needed only for a flextable made some other way.
Usage
apa_style(
x,
font_family = NULL,
font_size = NULL,
text_color = "black",
border_color = "black",
border_width = 0.5,
line_spacing = NULL,
horizontal_padding = 3,
table_align = "left",
header_align_vertical = c("top", "middle", "bottom"),
layout = "autofit",
table_width = NULL,
markdown = TRUE,
markdown_header = markdown,
markdown_body = markdown,
no_markdown_columns = NULL,
no_markdown_columns_header = no_markdown_columns,
separate_headers = TRUE
)
Arguments
x |
|
font_family |
font family (e.g., |
font_size |
font size, in points. If |
text_color |
color of the text: an R color name (e.g., |
border_color |
color of the rules, in the same forms as |
border_width |
width of the rules, in points (default: 0.5) |
line_spacing |
spacing between lines of the header and body (e.g., 2
for double spacing or 1 for single spacing). If |
horizontal_padding |
space to the left and right of each cell's contents, in points (default: 3) |
table_align |
alignment of the table on the page: |
header_align_vertical |
vertical alignment of header text when header
cells differ in height: |
layout |
|
table_width |
width of the table, in the same forms in every apa7
function: a proportion from 0 to 1 of the default width (the full width
of a portrait page unless changed with |
markdown |
if |
markdown_header, markdown_body |
whether the header or the body is
converted from markdown (both default to |
no_markdown_columns |
body columns whose text is shown as it is, not converted from markdown (unquoted or quoted names, or tidyselect helpers) |
no_markdown_columns_header |
column headers that are not converted
from markdown. By default, the same columns as |
separate_headers |
if |
Details
With a few minor details omitted, apa_style() does roughly this:
Separates the headers into column spanners and deckered heads at underscores, if
separate_headers = TRUEand the header has one row.Sets the font, font size, and text color of every cell.
Draws the three horizontal rules of an APA table: above the header, below the header, and below the body.
Top-aligns the body cells, centers the header text, and aligns the header cells vertically with
header_align_vertical.Adds space above and below each cell's text, (
line_spacing- 1) times 2/3 of the font size, so that rows have the spacing ofline_spacingwhile text that wraps within a cell stays single-spaced. In Typst output, the space is a little larger, because Typst measures lines differently than Word does. The left and right padding ishorizontal_padding.Styles apa7's helper columns. Break columns (from
add_break_columns()) are left empty. Star columns (fromadd_star_column()andseparate_star_column()) and list columns (fromadd_list_column()) have no header and no padding on the side next to the column they belong to, so that the two read as one column.Sets the table's layout, alignment on the page, and width (
layout,table_align, andtable_width). In Word, the table is kept on the same page as the text that follows it.Converts markdown in the header and the body with
ftExtra::colformat_md(), except in the columns named inno_markdown_columns_headerandno_markdown_columnsand in cells that are already formatted.If the first column is named
VariableorPredictor, left-aligns it.
Value
flextable::flextable
References
American Psychological Association. (2020). Publication manual of the American Psychological Association (7th ed.). doi:10.1037/0000165-000
Examples
d <- data.frame(x = 1:3, y = 4:6)
flextable::flextable(d) |>
apa_style()
Subgroup analysis table for a meta-analysis
Description
Makes an APA-style table of a subgroup analysis of a meta-analysis fit
with metafor::rma(): the pooled estimate of each subgroup, followed by
the overall pooled estimate, with the test of subgroup differences in the
note.
Usage
apa_subgroups(fit, subgroup, tau2 = c("separate", "common"), transform = TRUE)
Arguments
fit |
a meta-analysis without moderators fit with |
subgroup |
the subgroup variable: the name of a column in the data of
|
tau2 |
|
transform |
if |
Details
With tau2 = "separate" (default), each subgroup is pooled with its own
random-effects model (with the estimator of \tau^2 of fit),
and the subgroup estimates are compared with Q_{\text{between}}, the heterogeneity statistic of an equal-effects meta-analysis of
the subgroup estimates. With tau2 = "common", the subgroups share one
\tau^2: the estimates come from a mixed-effects
meta-regression with the subgroup as a categorical moderator, and the
subgroups are compared with the omnibus test of the moderator
(Q_{\text{M}}). The separate approach suits subgroups that may
differ in heterogeneity; the common approach gives more stable estimates
of \tau^2 when subgroups have few studies (Borenstein et al.,
2009, chap. 19).
Estimates are shown on the same scale as in apa_parameters() (e.g., risk
ratios are exponentiated, and Fisher's z values are converted back to
correlations).
Value
apa7_tbl (tibble)
References
Borenstein, M., Hedges, L. V., Higgins, J. P. T., & Rothstein, H. R. (2009). Introduction to meta-analysis. Wiley. doi:10.1002/9780470743386
Examples
if (requireNamespace("metafor", quietly = TRUE) &&
requireNamespace("metadat", quietly = TRUE)) {
d_bcg <- metafor::escalc(
measure = "RR",
ai = tpos, bi = tneg, ci = cpos, di = cneg,
data = metadat::dat.bcg
)
fit_meta <- metafor::rma(yi, vi, data = d_bcg)
apa_subgroups(fit_meta, alloc)
}
Column format class
Description
This class is used to define the format of columns in tables, including the name, header, latex representation, a formatter function, and what the header abbreviates.
Usage
column_format(
name = character(0),
header = character(0),
latex = character(0),
formatter = function() NULL,
abbreviation = character(0)
)
Arguments
name |
name of column |
header |
markdown representation of header name |
latex |
latex representation of header name |
formatter |
function that formats the column values. It should take a vector of values and return a character vector of formatted values. |
abbreviation |
what the header stands for, used by |
Details
A column_format is an S7 object. Its properties are read and changed with
@ (e.g., R2@header, or R2@formatter <- my_function). Formats are
collected in a column_formats() object, in which each format is read,
added, or replaced with $ (e.g., column_formats()$p). The table
functions use a format for every column with the same name as the format.
Value
column_format object
Examples
R2 <- column_format(
"R2",
header = "*R*^2^",
latex = "$R^2$",
formatter = \(x, accuracy = .01, ...) {
align_chr(x,
accuracy = accuracy,
trim_leading_zeros = TRUE,
...)
})
R2
R2@header
R2@formatter(c(.123, .45))
# Define an abbreviation in table notes
SS <- column_formats()$Sum_Squares
SS@abbreviation <- "sum of squares"
Create a set of column formats
Description
Returns an S7 object that contains a list of column_format objects that can be used to format parameters in APA style.
Usage
column_formats(
.data = NULL,
accuracy = NULL,
labels = character(0),
custom_columns = NULL,
variable_labels,
intercept_text,
starred_columns
)
Arguments
.data |
list of |
accuracy |
rounding accuracy of the formatters (e.g., |
labels |
named character vector of variable labels, named by the
variables (e.g., |
custom_columns |
named list of |
variable_labels |
deprecated; use |
intercept_text, starred_columns |
deprecated, and never used. Set the
label of the intercept row for all tables with
|
Details
Each column_format() in the list is named by the column it formats.
Formats are read, added, replaced, and removed with $ (e.g.,
my_formats$beta, my_formats$Predictor <- column_format("Predictor"), or
my_formats$beta <- NULL), and the properties of a single format are read
and changed with @ (e.g., my_formats$p@header). The get_ properties
listed under Slots return the names, headers, formatters, and so on of all
the formats at once (e.g., my_formats@get_tibble).
Use the object with the column_formats argument of apa_flextable(),
apa_format_columns(), and the table functions, or set it for every table
with apa7_defaults(column_formats = my_formats).
Value
column_formats
Slots
get_column_namesgetter for column names
get_headersgetter for column headers
get_latexgetter for column latex headers
get_formattersgetter for column formatters
get_header_renamegetter for column names with headers as names
get_header_rename_latexgetter for column names with latex headers as names
get_tibblegetter for tibble with column names, headers, latex headers, and formatters
get_abbreviationsgetter for the abbreviations defined by the column formats, as a character vector of definitions named by the term defined
Examples
my_formats <- column_formats()
my_formats$Coefficient@formatter <- \(x) round(x, 2)
my_formats$Coefficient@formatter(2.214)
Prepend column spanner labels to data column labels
Description
Prepend column spanner labels to data column labels
Usage
column_spanner_label(data, label, ..., relocate = TRUE)
Arguments
data |
data.frame or tibble |
label |
character of column spanner |
... |
columns (i.e., one or more tidyselect functions and/or a vector of quoted or unquoted variable names) |
relocate |
relocate columns with same spanner label to be adjacent |
Value
data.frame or tibble
Examples
d <- data.frame(y = 1:3, x1 = 2:4, x2 = 3:5)
# Unquoted variable names
column_spanner_label(d, "Label", c(x1, x2))
# Character values (quoted variable names)
column_spanner_label(d, "Label", c("x1", "x2"))
# Tidyselect function (e.g., starts_with, ends_with, contains)
column_spanner_label(d, "Label", dplyr::starts_with("x"))
# Tidyselect range
column_spanner_label(d, "Label", x1:x2)
# Selected variables are relocated after the first selected variable
column_spanner_label(d, "Label", c(x2, y))
Return markdown text with hanging indent
Description
Return markdown text with hanging indent
Usage
hanging_indent(
x,
indent = 4,
width = 30,
space = NULL,
newline = "\\\\\n",
whitespace_only = FALSE,
wrap_equal_width = FALSE
)
Arguments
x |
text |
indent |
number of |
width |
maximum number of characters per line |
space |
indenting character. If |
newline |
text inserted at each line break (default: a markdown hard line break, a backslash followed by a newline) |
whitespace_only |
if |
wrap_equal_width |
if |
Value
character vector
Examples
hanging_indent(
"Cohen, J. (1988). Statistical power analysis for the behavioral sciences (2nd ed.). Erlbaum."
)
Install the apaquarto extension
Description
A wrapper for quarto::quarto_add_extension
Two separate questions can be asked: whether to install R packages that
apaquarto needs (quarto, ragg, and svglite), controlled by ask, and
whether to trust and download the extension from GitHub, a question Quarto
itself asks, controlled by no_prompt.
Usage
install_apaquarto(
no_prompt = FALSE,
quiet = FALSE,
quarto_args = NULL,
ask = TRUE
)
Arguments
no_prompt |
if |
quiet |
if |
quarto_args |
character vector of other Quarto command-line arguments, appended to the |
ask |
if |
Value
installs the apaquarto Quarto extension
Examples
## Not run:
install_apaquarto()
## End(Not run)
Tests if a character vector contains numeric-like values
Description
Tests if a character vector contains numeric-like values
Usage
is_numeric_like(x, elementwise = FALSE)
Arguments
x |
character vector |
elementwise |
if |
Value
logical vector
Examples
is_numeric_like(c("-9", " 2.0", "-1.0 "))
is_numeric_like(c("9-", -1, "10"))
is_numeric_like(c("9", -1.2, "10"))
Run shiny app to make a document in APA style via Quarto
Description
A wrapper for shiny::runGitHub Note that running this function will install any missing packages needed to run the app: bsicons, bslib, conflicted, dplyr, fresh, purrr, ragg, rclipboard, readr, shiny, shinyWidgets, snakecase, svglite, tibble, tidyr, tippy, toastui, yaml
Usage
make_apaquarto(launch.browser = TRUE, ask = TRUE)
Arguments
launch.browser |
run shiny app in default browser |
ask |
if |
Value
Runs a shiny app that creates apaquarto documents
Examples
## Not run:
make_apaquarto()
## End(Not run)
Display latex matrices
Description
Display latex matrices
Usage
matrix_display(x, bracket = c("[", "(", "|", ""), include_names = TRUE)
Arguments
x |
a matrix |
bracket |
bracket around the matrix: |
include_names |
if |
Value
character
Examples
matrix_display(diag(2))
Pads text on the left or right so that the width is the same for each element of the vector
Description
num_pad() adds spaces to the left or right of each element of a text
vector so that all elements have the same width, counted in characters or
measured in a font. align_chr() uses it to line up numbers.
Usage
num_pad(
x,
pad_left = TRUE,
padding_character = " ",
NA_value = "",
font_family = NULL
)
Arguments
x |
vector of text |
pad_left |
if TRUE (default), pads on the left, otherwise pads on the right |
padding_character |
character to use for padding, default is |
NA_value |
value to replace NA |
font_family |
font in which to measure text widths. If |
Details
By default, text is padded with one padding_character per missing visible character. Markdown markup (e.g., **, *, ^, ~, and backslash escapes) is not counted. If font_family names an installed font, text is instead padded to equal rendered width in that font, using a combination of figure, punctuation, thin, and hair spaces (padding_character is then ignored). Superscripts and subscripts are measured at 2/3 of the font size.
Value
character vector
Examples
num_pad(c("a", "bb"))
# A minus sign (U+2212) and a figure-space-padded 1 have the same width
num_pad(c("\u22121", "1"), font_family = "Times New Roman")
Convert p-values to stars
Description
Convert p-values to stars
Usage
p2stars(
p,
alpha = c(0.05, 0.01, 0.001),
first_alpha_marginal = FALSE,
superscript = FALSE,
add_trailing_space = FALSE,
prefix = "\\"
)
Arguments
p |
vector of numbers |
alpha |
vector of thresholds |
first_alpha_marginal |
if TRUE, the first alpha value is treated as marginal and gets a dagger instead of a star |
superscript |
make as superscript |
add_trailing_space |
if TRUE, adds a trailing space after the stars (default: FALSE) |
prefix |
usually backslashes to prevent markdown from interpreting asterisks as bullets or italics |
Value
character vector
Examples
p2stars(c(.32, .02, .005),
alpha = c(.05, .01))
A wrapper for tidyr::pivot_wider that creates column names as name_variable instead of variable_name
Description
pivot_wider_name_first() reshapes data from long to wide like
tidyr::pivot_wider(), but it puts the value of names_from first in the
new column names (e.g., Model 1_t instead of t_Model 1). In
apa_flextable(), the names_from values then become column spanners.
Usage
pivot_wider_name_first(
data,
...,
id_cols = NULL,
id_expand = FALSE,
names_from = name,
names_prefix = "",
names_sep = "_",
names_sort = FALSE,
names_vary = "slowest",
names_expand = FALSE,
names_repair = "check_unique",
values_from = value,
values_fill = NULL,
values_fn = NULL,
unused_fn = NULL
)
Arguments
data |
A data frame to pivot. |
... |
Additional arguments passed on to methods. |
id_cols |
< Defaults to all columns in |
id_expand |
Should the values in the |
names_from, values_from |
< If |
names_prefix |
String added to the start of every variable name. This is
particularly useful if |
names_sep |
If |
names_sort |
Should the column names be sorted? If |
names_vary |
|
names_expand |
Should the values in the |
names_repair |
What happens if the output has invalid column names?
The default, |
values_fill |
Optionally, a (scalar) value that specifies what each
This can be a named list if you want to apply different fill values to different value columns. |
values_fn |
Optionally, a function applied to the value in each cell
in the output. You will typically use this when the combination of
This can be a named list if you want to apply different aggregations
to different |
unused_fn |
Optionally, a function applied to summarize the values from
the unused columns (i.e. columns not identified by The default drops all unused columns from the result. This can be a named list if you want to apply different aggregations to different unused columns.
This is similar to grouping by the |
Details
The new column names are made of names_prefix, the value of
names_from, names_sep, and the name of the values_from column, in
that order (e.g., names_prefix = "Model " gives Model 1_t). Only one
names_from column is allowed.
Unlike in tidyr::pivot_wider(), names_vary defaults to "slowest",
which keeps the columns of each names_from value next to each other
(e.g., Model 1_t, Model 1_p, Model 2_t, Model 2_p). Two settings
keep apa_flextable() from making one spanner per names_from value:
names_vary = "fastest", which interleaves the columns (Model 1_t,
Model 2_t, Model 1_p, Model 2_p), and a names_sep other than an
underscore, which apa_flextable() does not split into header rows.
Value
data.frame
Examples
d <- data.frame(Model = 1:2, t = c(2.1, 0.8), p = c(.04, .45))
pivot_wider_name_first(d, names_from = Model, values_from = c(t, p),
names_prefix = "Model ")
# For comparison:
tidyr::pivot_wider(d, names_from = Model, values_from = c(t, p))
Fit column widths to the contents and the table width
Description
pretty_widths() sets each column's width to fit its contents and then
scales the widths so that the table has the width given by table_width.
Usage
pretty_widths(
x,
min_width = 0.05,
unit = c("in", "cm", "mm"),
table_width = NULL
)
Arguments
x |
flextable |
min_width |
minimum width of columns |
unit |
unit of the column widths: |
table_width |
width of the table, in the same forms in every apa7
function: a proportion from 0 to 1 of the default width (the full width
of a portrait page unless changed with |
Details
The widths are first measured with flextable::dim_pretty(), and no column
is narrower than min_width. If the table width is 0, these widths are kept.
Otherwise, they are scaled up or down in proportion so that they add up to
the table width, with two exceptions:
Break columns (from
add_break_columns()) are kept atmin_width.List columns (from
add_list_column()) keep their measured width, and the column to the right of each one (the text of the list) gets the extra width instead.
The table's layout is then set to "fixed", so that Word keeps the widths.
If table_width is NULL (default), the width is taken from the code
chunk's options or from apa7_defaults() (see the table_width argument).
With the defaults, the table is as wide as the text on a portrait page.
Value
flextable::flextable
Examples
ft <- flextable::flextable(head(mtcars[, 1:4]))
# Widths fitted to the contents
pretty_widths(ft)
# Widths stretched to a total of 4 inches
pretty_widths(ft, table_width = c(inches = 4))
Scientific notation for markdown
Description
Scientific notation for markdown
Usage
sci_md(x, digits = 2, lb = 0.0095, ub = 99.5, align = FALSE)
Arguments
x |
numeric vector |
digits |
number of decimal places (of the mantissa, for numbers in scientific notation) |
lb, ub |
numbers at or below |
align |
if |
Value
A character vector
Examples
sci_md(c(.0045,1.44, 24567857.45))
Add columns that separate significance stars from numbers
Description
Add columns that separate significance stars from numbers
Usage
separate_star_column(
data,
...,
superscript = TRUE,
star = "\\*",
star_replace = "\\\\*"
)
Arguments
data |
data.frame or tibble |
... |
Column name or tidyselect function. Select columns |
superscript |
make stars superscript |
star |
character to use for stars (default: "\*") |
star_replace |
character to replace stars with (default: "\\*") |
Value
data.frame or tibble
Examples
tibble::tibble(x = c(".45", ".58*", ".68**"),
y = c(1,2,3),
z = 4:6) |>
separate_star_column(x)
Prefix text with figure spaces to balance star text
Description
Prefix text with figure spaces to balance star text
Usage
star_balance(x, star = "\\*", superscript = TRUE)
Arguments
x |
character vector |
star |
star text |
superscript |
Place superscript text if |
Value
character vector
Examples
# Starred values get one figure space per star on the left,
# so that the numbers line up when the column is centered
star_balance(c(".32", ".04\\^\\*\\^", ".005\\^\\*\\*\\^"))
Like stringr::str_wrap, but attempts to create lines of equal width
Description
Like stringr::str_wrap, but attempts to create lines of equal width
Usage
str_wrap_equal(x, max_width = 30L, sep = "\n")
Arguments
x |
character |
max_width |
maximum number of characters per line |
sep |
text inserted at each line break |
Value
character
Examples
str_wrap_equal("This function attempts to split the string into lines with roughly equal width.")
Surrounds text with tags unless empty
Description
Surrounds text with tags unless empty
Usage
tagger(x, tag = "<span>", right_tag = gsub("^<", "</", tag))
bold_md(x)
italic_md(x)
superscript_md(x)
subscript_md(x)
header_md(x, level = 1)
Arguments
x |
character vector |
tag |
opening tag, e.g., |
right_tag |
closing tag. By default, the opening tag with |
level |
heading level |
Value
character vector
Examples
x <- c("hello", "", NA)
tagger(x, "<span>")
bold_md(x)
italic_md(x)
superscript_md(x)
subscript_md(x)
header_md("Level 1")
header_md("Level 2", 2)