Package {apa7}


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 ORCID iD [aut, cre, cph]
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:

See Also

Useful links:


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., ends_with("_mean"))

.before

if TRUE, break columns are inserted before the selected columns instead of after them (default: FALSE)

omit_first

if TRUE, no break column is inserted at the first selected column

omit_last

if TRUE, no break column is inserted at the last selected column

d

deprecated; use data

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: "1" (default) for 1, 2, 3; "a" for a, b, c; "A" for A, B, C; "i" for i, ii, iii; or "I" for I, II, III

sep

text between the list label and the item (default: ". ", as in "1. ")

merge

If TRUE, list columns will be united with their respective text columns.

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: FALSE)

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 apa7_defaults() will be used.

trim_leading_zeros

if TRUE, leading zeros are removed (e.g., .45 instead of 0.45), as APA style requires for values that cannot exceed 1 (correlations, proportions, p-values). If FALSE (default), they are kept.

drop0trailing

Drop trailing zeros

add_plusses

if TRUE, positive numbers get a plus sign. If FALSE (default), they do not.

padding_character

character to use for padding, default is ⁠&numsp;⁠ (figure space). With the default, text is padded to equal rendered width in the default font family (see num_pad() and the width_aware_padding argument of apa7_defaults()).

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 signs::signs()

Details

With a few minor details omitted, align_chr() does roughly this:

  1. If format_numeric_character = TRUE, converts text made only of digits, minus signs, and periods to numbers.

  2. Formats numbers with signs::signs(): rounds them to accuracy, replaces hyphens with true minus signs, and adds commas to large numbers. Plus signs are added if add_plusses = TRUE, leading zeros are removed if trim_leading_zeros = TRUE, and trailing zeros are dropped if drop0trailing = TRUE. Whole numbers are not given decimals unless format_integers = TRUE.

  3. Splits each value at the first center character, then pads the part before it on the left and the part after it on the right (side limits 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 apa_parameters() and apa_anova() use it. Descriptive tables such as apa_descriptives(), apa_cor(), and apa_loadings() have their own digits argument instead (digits = 2 is the same as accuracy = .01).

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: "Constant")

column_formats

a column_formats() object: the headers, formatters, and note definitions of table columns

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 accuracy and returns a character vector. By default, align_chr() with the accuracy setting.

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, align_chr() with trim_leading_zeros = TRUE. Note that this is a function, unlike the TRUE/FALSE trim_leading_zeros argument of align_chr().

width_aware_padding

if TRUE (default), align_chr() pads text to equal rendered width in font_family (when the font is installed). If FALSE, text is padded with one figure space per missing character.

page_width

width of the text area of a portrait page, which tables fill with table_width = "page" (or 1, by default): a number (in inches) or the name of a paper size, whose width less APA's 1-inch margins on each side is used (e.g., "us-letter" gives 6.5 inches, the default, and "a4" gives 6.27 inches). If not set, the width comes from the paper and margins of the document being rendered, if any (see Details). Paper sizes are those of Typst's page function (e.g., "a4", "a5", "us-letter", "us-legal", "jis-b5"); see https://typst.app/docs/reference/layout/page/#parameters-paper.

landscape_width

width of the text area of a landscape page, in inches, which tables fill with table_width = "landscape". If NA (default), the height of the paper named by page_width less 1-inch margins (9 inches for "us-letter" and 9.69 inches for "a4"). When page_width is a number, the paper is taken to have the proportions of letter-size paper.

column_width

width of one column of a two-column page, in inches, which tables fill with table_width = "column". If NA (default), the width of a column in apaquarto's two-column journal mode (documentmode: jou): the paper width less 0.75-inch margins, less a gutter of 4% between the columns, divided by 2 (3.36 inches for "us-letter" and 3.25 inches for "a4"). When page_width is a number, the paper is taken to be that number plus 1-inch margins.

table_width

default width of tables, in any of the forms that the table_width argument of apa_flextable() takes: 1 (default) for the full width of a portrait page, a proportion of it (e.g., .8), "page", "landscape", "column", or a named number (e.g., c(column = 1)). In a two-column document, table_width = "column" makes tables as wide as a column, and a proportion given to a table function is then a proportion of the column. If not set, tables in a document in apaquarto's journal mode (documentmode: jou) are as wide as a column.

print

how tables made by apa7 functions (see apa7_tbl) are displayed: "auto" (default) as tables in Quarto and R Markdown documents and as tibbles in the console, "flextable" as tables everywhere, or "tibble" as tibbles everywhere

citations

how articles cited in table notes are written: "auto" (default), "keys", or "text". See apa7_write_bib().

reset

if TRUE, reset all defaults (except as specified)

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 apa7_tbl

...

arguments passed to the next method

Details

The apa7.print option (also set with apa7_defaults(print = )) controls this behavior:

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 TRUE (default), an existing file is replaced

Details

Citations in notes take one of two forms:

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 aov or lm model, a repeated-measures aov model with an Error() term (class aovlist), an afex model (class afex_aov), a linear mixed model from lme4::lmer() or lmerTest::lmer(), a multivariate model from stats::manova() or from stats::lm() with several outcomes (class mlm), or an ANOVA table from stats::anova(), car::Anova(), or lmerTest's anova().

anova_parameters

columns to display. "Effect_Size" stands for whichever effect size effect_size, partial, and generalized select, and "CI" adds its confidence interval as [LL, UL]. Columns not in the ANOVA table are silently dropped.

effect_size

effect size to display: "eta" (\eta^2, default), "omega" (\omega^2), or "epsilon" (\epsilon^2). If NULL, no effect size is computed.

partial

if TRUE (default), partial effect sizes (e.g., \eta^2_p) are displayed. For one-way designs, partial and non-partial effect sizes are the same.

generalized

if TRUE, generalized \eta^2 (\eta^2_G) is displayed instead, which is comparable across between- and within-subjects designs. Only for effect_size = "eta".

type

type of sums of squares for aov and lm models: 1 (sequential, default, as in stats::anova()), 2, or 3. Types 2 and 3 are computed with car::Anova(). Type 3 tests are interpretable only when factors have sum-to-zero contrasts (e.g., contr.sum) and covariates are centered. For linear mixed models, the type of hypothesis tests: 3 (default, as in lmerTest), 2, or 1. Ignored for ANOVA tables, which already have a type.

ci

confidence level for the effect size interval, shown if anova_parameters includes "CI". Intervals are two-sided, so a 90% interval excludes 0 when the F test is significant at \alpha = .05, and its lower bound is 0 otherwise. Intervals are not shown for generalized \eta^2, because those computed by effectsize can exclude the point estimate.

residual_label

label for residual (error) rows

starred

columns to star with significant p-values (e.g., "F")

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 parameters::model_parameters()

ddf

for linear mixed models, method of approximating the denominator degrees of freedom: "Kenward-Roger" (default) or "Satterthwaite"

test

for multivariate models, the multivariate test statistic: "Pillai" (default), "Wilks", "Hotelling-Lawley", or "Roy". For car::Anova() tables, the statistic of the table by default.

univariate

for multivariate models, if TRUE, the univariate ANOVA of each outcome instead of the multivariate tests. The outcomes must be given with cbind() in the model formula.

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., smoking or "smoking")

by

variable whose levels are the columns of the table, unquoted or quoted. If data has exactly two columns, variable and by can be left out: the first column is then by, and the second is variable (as in earlier versions of apa7).

percent

percentages shown next to the counts: "column" (default) for percentages of each column's total, "row" for percentages of each row's total, "total" for percentages of the whole sample, or "none" for counts only

total

if TRUE (default), a "Total" row and column are added

test

"chisq" (default) for the chi-square test of independence, "fisher" for Fisher's exact test, or "none" for no test

correct

if TRUE (default), the chi-square test of a 2 × 2 table uses Yates's continuity correction

effect_size

"auto" (default) for \phi in 2 × 2 tables and Cramér's V otherwise, "cramers_v", "phi" (2 × 2 tables only), or "none"

percent_digits

number of decimal places of percentages

labels

named character vector of labels for variable and by (e.g., c(smoke = "Smoking")). Variables without a label are named by their formatted names.

format_variable_names

format the names of variables that have no label with the Variable column format

...

deprecated arguments of earlier versions of apa_chisq() (note, suppress_warnings, and the styling arguments of apa_flextable()). If any is given, a flextable is returned, as before, with a warning.

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 performance::check_collinearity() accepts, e.g., lm, glm, lme4, glmmTMB, or pscl models), or the output of performance::check_collinearity()

columns

columns to display, in order: any of "VIF", "VIF_CI" (confidence interval of VIF), "SE_factor" (\sqrt{VIF}, the factor by which the standard error is inflated), "Tolerance", and "Tolerance_CI"

flag

NULL (default) or a number: VIFs at or above it are bolded (e.g., flag = 5 or flag = 10), and the note says so

ci

confidence level of the intervals

format_variable_names

if TRUE (default), term names are formatted as in apa_parameters() (e.g., "factor(cyl)" becomes "Cyl", and "wt:hp" becomes "Wt \times Hp"). Set to FALSE to keep the names exactly as performance::check_collinearity() gives them.

digits

number of decimal places (unaffected by apa7_defaults(accuracy = ))

...

arguments passed to performance::check_collinearity() (e.g., component)

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 correlation::correlation() (see Details)

alpha

p-value thresholds for significance stars, from largest to smallest (default: c(.05, .01, .001), for one, two, and three stars). With bold_significant = TRUE, only the first is used.

digits

number of decimal places of the correlations (unaffected by apa7_defaults(accuracy = ))

bold_significant

if TRUE, correlations with p below the first alpha are bolded instead of starred. If FALSE (default), they are not.

star_significant

if TRUE (default), significant correlations get stars (one for each alpha they are below). Ignored when bold_significant = TRUE. Model tables such as apa_parameters() do the same with their starred and bolded arguments.

significance_note

if TRUE (default), the note explains the stars (or the bolding) when any correlation is significant

keep_empty_star_columns

if TRUE (default), every correlation column keeps its star column, even when no correlation in it is significant, so that the columns have the same width. If FALSE, empty star columns are removed.

summary_functions

Any named list of functions that summarize data columns (e.g., list(Mean = mean, SD = sd)). Can also be a character vector of function names (e.g., c("n", "M", "SD")). Functions available in a character vector: IQR, Interquartile Range, Kurtosis, MAD, Median Absolute Deviation, M, Mean, Med, Median, n, N, Quantile, Range, SD, Skewness, Var, Variance

column_formats

column_formats() object that formats the summary columns (e.g., M and SD). If NULL (default), the column formats set with apa7_defaults().

method

kind of correlation (e.g., "pearson", "spearman", "kendall", "biweight", or "percentage"), passed to correlation::correlation(). Not used for correlation::correlation() output.

p_adjust

method of adjusting the p-values (and so the stars) for multiple comparisons (e.g., "holm", "bonferroni", or "fdr"). Unlike correlation::correlation(), the default is "none". Not used for correlation::correlation() output.

partial

if TRUE, partial correlations, each controlling for all other variables in the table. Not used for correlation::correlation() output.

...

other arguments passed to correlation::correlation() (e.g., robust = TRUE, winsorize = .2, or multilevel = TRUE). Not used for correlation::correlation() output.

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 output = "tibble", which returns the table). Pass the table to apa_flextable() instead, which takes the same styling arguments, with note = TRUE for the note or a character string for a note of your own.

p_value

deprecated; use alpha

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., c(age, income) or c("age", "income")) or tidyselect helpers (e.g., starts_with("item") or where(is.numeric)). If NULL (default), all columns. The by variable is never described.

by

grouping variable, unquoted or quoted (e.g., group or "group"). If given, each group gets a column.

total

if TRUE (default), a column for the whole sample is added when there are groups

continuous

how continuous variables are described: "mean_sd" (default) for M (SD), or "median_iqr" for Mdn (IQR). A named vector sets it for particular variables (e.g., c(income = "median_iqr")), and other variables use "mean_sd".

categorical

numeric variables to treat as categorical, selected like variables

labels

named character vector of variable labels (e.g., c(age = "Age (years)")). Variables without a label are named by their formatted names.

test

tests of the differences between groups (requires by): "none" (default) for no tests, or a column of p-values with categorical variables tested by Fisher's exact test when an expected count is below 5 and the chi-square test otherwise ("auto"), by the chi-square test ("chisq"), or by Fisher's exact test ("fisher"). Continuous variables are tested the same way in each case (see Details). TRUE is the same as "auto", and FALSE the same as "none".

missing

where missing values are reported: "note" (default) in the note, or "row" in a "Missing" row below each variable that has missing values

range

if TRUE, a "Range" row with the minimum and maximum is added below each continuous variable

digits

number of decimal places of means, standard deviations, medians, interquartile ranges, and ranges (unaffected by apa7_defaults(accuracy = ))

percent_digits

number of decimal places of percentages

format_variable_names

format variable names that have no label with the Variable column format

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 psych::fa, psych::principal, parameters::factor_analysis, parameters::principal_components, or lavaan object

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., c(PA1 = "Verbal")). The unnamed form is safer: after an oblimin rotation, the labels psych assigns (PA1, PA2, ...) can change from one run to the next, but the order of the factors does not.

digits

number of decimal places (unaffected by apa7_defaults(accuracy = ))

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: "left" (default), "center", or "right"

row_title_prefix

text placed before each heading (e.g., "Group" gives "Group A")

row_title_sep

text between row_title_prefix and the heading (default: a space)

row_title_border

border drawn around each group of rows: a list of color, style, and width (in points), as in officer::fp_border()

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 row_title_column and row_title_align = "left")

col_keys

columns to display, in order (default: all columns of data), passed to flextable::flextable()

cwidth, cheight

initial cell width and height in inches, passed to flextable::flextable(). With pretty_widths = TRUE (default), the widths are then fitted to the contents and table_width.

header_align_vertical

vertical alignment of header text when header cells differ in height: "top" (default), "middle", or "bottom"

separate_headers

if TRUE (default), column names with an underscore become two header rows: the part before it is a column spanner over the columns that share it (e.g., ⁠Model 1_B⁠ and ⁠Model 1_SE⁠ share a "Model 1" spanner)

apa_style

if TRUE (default), apa_style() is applied (fonts, borders, spacing, and markdown)

font_family

font family (e.g., "Times New Roman" or "Arial"). If NULL (default), the font set with apa7_defaults(font_family = ) (Times New Roman unless changed).

font_size

font size, in points. If NULL (default), the size set with apa7_defaults(font_size = ) (12 unless changed).

text_color

color of the text: an R color name (e.g., "black", the default) or a hex code (e.g., "#333333")

border_color

color of the rules, in the same forms as text_color

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 NULL (default), the spacing set with apa7_defaults(line_spacing = ) (2 unless changed). Table notes are single-spaced.

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: "left" (default), "center", or "right"

layout

"autofit" (default) lets the column widths adjust to the contents in Word; "fixed" keeps the widths as set (see flextable::set_table_properties())

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 apa7_defaults(table_width = )), "page" (or "portrait") for the full width of a portrait page, "landscape" for a landscape page, "column" for one column of a two-column page, or a named number: a proportion of one of these widths (e.g., c(landscape = .8)) or a width in inches, cm, or mm (e.g., c(inches = 5)). With 0, the columns are only as wide as their contents need. If NULL (default), the width set by the code chunk's apa7-width option in Quarto (e.g., ⁠#| apa7-width: landscape⁠, or ⁠#| apa7-width: {landscape: .8}⁠ for a named number) or apa7.width option in R Markdown, or "page" for a chunk with apaquarto's apa-twocolumn: true; otherwise, the table_width set with apa7_defaults() (1 unless changed). The widths of the pages and the column are set with the page_width, landscape_width, and column_width arguments of apa7_defaults(). A number greater than 1 is read as inches, with a warning to write it as c(inches = ).

markdown

if TRUE (default), text in the header and body is converted from markdown (e.g., ⁠*p*⁠ becomes an italic p)

markdown_header, markdown_body

whether the header or the body is converted from markdown (both default to markdown)

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 NULL (default), every header is treated as markdown. (In apa_style(), the default is no_markdown_columns. Here it differs because numeric columns are added to no_markdown_columns, and their headers still need markdown.)

no_format_columns

Column name or tidyselect function. selected columns are not formatted. Columns named in a "no_format_columns" attribute of data (set by functions such as apa_loadings()) are not formatted either. Likewise, a rule is drawn above the first body row whose first-column text matches a "rule_above" attribute of data.

auto_format_columns

if TRUE (default), columns whose names have a format in column_formats (e.g., p, SE, or R2) are formatted and given APA headers with apa_format_columns()

column_formats

a column_formats() object. If NULL (default), the column formats set with apa7_defaults().

pretty_widths

if TRUE (default), column widths are fitted to the contents and to table_width with pretty_widths()

add_breaks_between_spanners

if TRUE (default), a narrow empty column separates adjacent column spanners (see separate_headers), so that their rules do not touch

note

table note placed below the table, after "Note.". The note is single-spaced. If TRUE, the note is written by apa_note() from what a table function such as apa_anova(), apa_parameters(), or apa_loadings() recorded. A character string is used as the note (markdown is allowed), and NULL or FALSE (default) adds no note. Use this for documents that are not made with apaquarto. With apaquarto, use the apa-note chunk option instead (e.g., ⁠#| apa-note: !expr apa7::apa_note(tbl)⁠), so that the note is placed and styled by apaquarto and is not added twice.

...

passed to apa_style(). Every argument of apa_style() is also an argument of apa_flextable(), so this is rarely needed.

Details

With a few minor details omitted, apa_flextable does roughly this:

  1. Adds a break column between adjacent column spanners, if add_breaks_between_spanners = TRUE and separate_headers = TRUE. A break column is a narrow blank column without borders, so the rules under adjacent spanners do not touch.

  2. 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 with apa_format_columns(). Columns named in no_format_columns, or in a "no_format_columns" attribute of the data (set by functions such as apa_loadings()), are left as they are.

  3. Makes the flextable. With row_title_column, it first restructures the data with flextable::as_grouped_data(), and each row title gets a rule above it (row_title_border).

  4. Separates the headers into spanners and deckered heads, if separate_headers = TRUE.

  5. Left-aligns the first column and centers the columns of numbers.

  6. Applies apa_style() to style the table and convert markdown, if apa_style = TRUE.

  7. Aligns the row titles (row_title_align) and indents the rows under them (left_column_padding).

  8. Sets the column widths with pretty_widths(), if pretty_widths = TRUE.

  9. Lines up numbers padded by align_chr() on their decimal points.

  10. Draws a rule above the rows named in a "rule_above" attribute of the data (set by functions such as apa_loadings() and apa_chisq()).

  11. Adds the note, if note is 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

column_formats object. If NULL, the current default formatter set with apa7_defaults() will be used.

no_format_columns

Column name or tidyselect function. selected columns are not formatted

rename_headers

if TRUE, rename headers with markdown or latex

latex_headers

if TRUE, rename headers with latex instead of markdown

format_separated_headers

if TRUE, format headers with separated names. For example, if the formatter formats column R2 as ⁠*R*^2^⁠, then ⁠Model 1_R2⁠ becomes ⁠Model 1_*R*^2^⁠)

sep

separator for separated headers (default is "_")

accuracy

numeric (default: NULL, uses the current default accuracy set with apa7_defaults()). If not NULL, sets the accuracy for the formatter.

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 ⁠*&beta;*⁠), 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:

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 htest object from stats::t.test(), stats::wilcox.test(), stats::cor.test(), or stats::chisq.test(), or a list of such objects of the same kind (named lists label the rows). See Test results.

formula

two-sided formula with outcome variables on the left and a grouping or predictor variable on the right. Several outcomes are joined with + (e.g., mpg + hp ~ am), and each gets its own row. For one-sample t tests and Wilcoxon signed-rank tests, use 1 on the right (e.g., mpg ~ 1). For paired tests, put each pair of variables in Pair() with 1 on the right (e.g., Pair(pre, post) ~ 1, or Pair(anx1, anx2) + Pair(dep1, dep2) ~ 1 for several pairs).

test

type of test:

  • "t": t test comparing the means of two groups (Welch's test unless var_equal = TRUE), a paired t test, or a one-sample t test comparing a mean with mu

  • "wilcoxon": Wilcoxon rank-sum test comparing two groups, or a Wilcoxon signed-rank test of paired variables or of a variable compared with mu

  • "cor": correlation test of each outcome with the variable on the right

  • "chisq": chi-square test of independence of each outcome with the variable on the right

effect_size

effect size to display. If NULL (default), the effect size is Cohen's d ("cohens_d") for t tests, the rank-biserial correlation ("rank_biserial") for Wilcoxon tests, and Cramér's V ("cramers_v") for chi-square tests. t tests can also show Hedges' g ("hedges_g"), and chi-square tests can show \phi ("phi", for 2 \times 2 tables) or Cohen's w ("cohens_w"). Use "none" for no effect size. Correlation tests show the correlation itself.

For paired t tests, Cohen's d is d~av~ ("d_av"), which divides the mean difference by the average of the two variables' standard deviations, so it is comparable to d for two independent groups. Other choices are d~z~ ("d_z", divided by the standard deviation of the differences) and d~rm~ ("d_rm", d~z~ corrected for the correlation between the variables), and Hedges' g versions with a small-sample correction ("g_av", "g_z", "g_rm"; "hedges_g" is "g_av"). These come from effectsize::repeated_measures_d().

ci

confidence level of the effect size interval (for correlation tests, the interval of Pearson's r). Intervals are two-sided.

var_equal

if TRUE, two-group t tests assume equal variances (Student's t test), and Cohen's d uses the pooled standard deviation. If FALSE (default), Welch's t test is used, and Cohen's d uses the average of the two groups' variances.

mu

value that one-sample tests compare each variable with (for two-group tests, the hypothesized difference in location)

method

correlation coefficient: "pearson" (default), "spearman", or "kendall"

descriptives

if TRUE (default), the table shows each group's mean and standard deviation (t tests) or median (Wilcoxon tests), or each variable's sample size (correlation and chi-square tests).

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., c("Pretest", "Posttest")). If NULL (default), the headings are the variable names when there is one pair, and "First" and "Second" otherwise.

starred

columns to star with significant p-values (e.g., "t")

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., alternative = "greater", or correct = FALSE for stats::chisq.test())

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:

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 psych::fa, psych::principal, parameters::factor_analysis, parameters::principal_components, or lavaan object

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 psych::fa.sort()). If FALSE, the rows keep the order of the model (for lavaan models, the order of the model syntax).

min_loading

minimum absolute loading to display. Use NA or 0 to show all loadings. Defaults to .2, except for lavaan models, whose estimated loadings are all shown.

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., c(PA1 = "Verbal")). The unnamed form is safer: after an oblimin rotation, the labels psych assigns (PA1, PA2, ...) can change from one run to the next, but the order of the factors does not.

variance

if TRUE, rows are added for the variance explained by each factor (sums of squared loadings, proportion, and cumulative proportion). Not to be confused with the variances argument of apa_parameters() for lavaan models, which adds residual variances.

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 Variable column format. Set to FALSE to keep item text exactly as it is.

digits

number of decimal places for loadings (unaffected by apa7_defaults(accuracy = ))

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 modelbased::estimate_means() (for apa_means()), modelbased::estimate_contrasts() (for apa_contrasts()), or modelbased::estimate_slopes() (for apa_slopes())

by

variables whose levels (or values) the estimates are computed at (e.g., by = Species, by = c(am, cyl), by = "hp=[sd]", or by = list(hp = "[sd]")). Variable names can be quoted or unquoted, but values (e.g., "hp=[fivenum]") must be quoted. In apa_means() and apa_slopes(), the last variable labels the rows and the others get heading rows; in apa_contrasts(), all of them get heading rows. Passed to the modelbased function.

...

other arguments passed to the modelbased function when fit is a model (e.g., p_adjust = "holm", predict = "link", or estimate = "average")

starred

columns to which significance stars are added (e.g., "p" or "Estimate")

bolded

columns that are bolded when p \le .05

column_formats

column_formats() object. If NULL (default), the defaults are used. The estimate column is named "Estimate".

format_variable_names

if TRUE (default), variable names are formatted (e.g., "Sepal.Length" becomes "Sepal Length"). Factor levels are shown as they are.

contrast

variable whose levels (or values) are compared (e.g., contrast = cyl), quoted or unquoted. Passed to modelbased::estimate_contrasts().

effect_size

in apa_contrasts(), whether to add Cohen's d and its confidence interval. If NULL (default), d is added when it can be computed (models of continuous outcomes with an identity link, such as lm(), or any model when sd is given). If TRUE, an error is given when it cannot be computed.

sd

in apa_contrasts(), the standard deviation that differences are divided by to compute Cohen's d. If NULL (default), the model's residual standard deviation is used (not for mixed models).

trend

predictor whose slopes are estimated (e.g., trend = wt), quoted or unquoted. Passed to modelbased::estimate_slopes().

johnson_neyman

in apa_slopes(), whether the note gives the Johnson-Neyman intervals. If NULL (default), they are given when they can be computed (see Details). If TRUE, an error is given when they cannot be computed.

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 parameters::n_factors(), or a data frame passed to it

table

"methods" (default) for a row per method, or "agreement" for a row per suggested number of factors

bold_consensus

if TRUE (default), the numbers of factors supported by the most methods are bolded (methods table only)

format_method_names

if TRUE (default), method names are spelled out (e.g., "Velicer's MAP" becomes "Velicer's minimum average partial (MAP)" and "beta" becomes "Multiple regression (\beta)"). Set to FALSE to keep the names exactly as parameters::n_factors() gives them.

components

if TRUE, the table and note speak of components rather than factors. If NULL (default), components are assumed when fit is a data frame and type = "PCA" is passed in .... The output of parameters::n_factors() and parameters::n_components() does not record which was estimated, so set components = TRUE for the output of parameters::n_components().

...

arguments passed to parameters::n_factors() when fit is a data frame (e.g., type, rotation, algorithm, and package)

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: apa_anova(), apa_parameters(), apa_performance() (for lavaan and metafor models), apa_htest(), apa_chisq(), apa_cor(), apa_descriptives(), apa_means(), apa_contrasts(), apa_slopes(), apa_loadings(), apa_factor_cor(), apa_n_factors(), apa_reliability(), apa_collinearity(), apa_publication_bias(), or apa_subgroups(). Call apa_note() before changing the table, because some operations (e.g., dplyr::bind_rows()) drop the information it needs.

collapse

string that joins the sentences. Use NULL to get a character vector with one sentence per element.

citations

how articles cited in the note are written: "auto", "keys" (Pandoc citation keys, e.g., ⁠[@duvalTrimFillSimple2000]⁠), or "text" (e.g., "(Duval & Tweedie, 2000)"). If NULL (default), the apa7.citations option is used, which is "auto" unless set. See apa7_write_bib().

Details

For apa_anova() tables, the note can say

For apa_loadings() tables, the note can say

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

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

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 TRUE, the symbol and relation are included (e.g., p = .04 or p < .001), for use in running text (one p-value at a time). If FALSE (default), only the number is returned (e.g., .04 or <.001), for use in tables.

markdown

if TRUE (default), the output is markdown (e.g., ⁠*p*⁠ in italics). If FALSE, it is plain text, which can be used in LaTeX.

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 TRUE

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 alpha

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: lm, glm (including MASS::glm.nb), aov, aovlist, afex_aov, ordinal (MASS::polr, ordinal::clm), mixed (lme4::lmer, lme4::glmer, glmmTMB::glmmTMB, nlme::lme), generalized additive (mgcv::gam, mgcv::bam), structural equation (lavaan), meta-analysis (metafor::rma), multinomial (nnet::multinom), zero-inflated and hurdle (pscl::zeroinfl, pscl::hurdle), beta (betareg::betareg), quantile (quantreg::rq), robust (MASS::rlm, robustbase::lmrob), survival (survival::coxph, survival::survreg), ordinal mixed (ordinal::clmm), generalized estimating equations (geepack::geeglm), or multivariate linear (lm(cbind(y1, y2) ~ x)) models, or a named list of models of the same kind (see performance_parameters)

predictor_parameters

columns to display, in order, named as in parameters::model_parameters(): "Parameter", "Coefficient", "SE", "Std_Coefficient" (standardized coefficient, \beta), "CI", "t", "z", "df_error", "p", and, for models with a log or logit link, "Exp_Coefficient" and "Exp_CI". If named vector, column names will be vector names. Columns not present in the model output (e.g., t for a model tested with z) are silently dropped. For lists of models, NULL (default) uses the default for each model's class. Add "CI" to show confidence intervals as [LL, UL] (headed, e.g., "95% CI"), and, for glm, polr, and clm models, "Exp_CI" to show confidence intervals of exponentiated coefficients (headed, e.g., "95% CI for OR"). Confidence intervals are not shown by default.

starred

columns to which significance stars are added (e.g., "Coefficient" or "p"). NULL or NA for none.

bolded

columns whose values are bolded when p \le .05 (e.g., "Coefficient"). NULL or NA (default) for none.

column_formats

column_formats() object to format columns. If NULL (default), the column formats set with apa7_defaults().

t_with_df

if TRUE (default), the t column header includes the degrees of freedom (e.g., t(29)), and the df column is dropped, when all rows have the same df. If FALSE, t and df are separate columns.

...

arguments passed to methods. For lm, glm, polr, and clm models, further arguments are passed to parameters::model_parameters(). For example, vcov = "HC3" gives heteroskedasticity-consistent (robust) standard errors, and the test statistics, p-values, and confidence intervals are based on them. ci = .90 sets the confidence level.

exponentiate

if NULL (default), exponentiated coefficients are added when the model's link function is logit or log (i.e., odds ratios, risk ratios, or incidence rate ratios); for beta regression models, only for a logit link of the mean; for parametric survival models (survival::survreg), when the distribution models log time (time ratios). Cox models (survival::coxph) default to TRUE (hazard ratios). If TRUE, exponentiated coefficients are always added. If FALSE, they are never added.

component_headings

for models with two components, if TRUE (default), each component is introduced by a heading row, with its coefficients indented below it. If FALSE, there are no heading rows, and the second component's coefficients are labeled instead: "Precision: " for the precision model of beta regression models (betareg::betareg), and "Zero-inflation: " or "Zero hurdle: " for the zero model of zero-inflated and hurdle models (pscl::zeroinfl, pscl::hurdle).

thresholds

for ordinal models, if TRUE (default), threshold (cutpoint) rows are displayed below the predictors. For lavaan models, if TRUE, a section for the thresholds of ordinal indicators is added (FALSE by default).

random

for mixed models, if TRUE (default), random-effect standard deviations and correlations (and the residual standard deviation, for linear mixed models) are displayed below the fixed effects.

effect_headings

for mixed models, if TRUE (default), the fixed and random effects are introduced by heading rows ("Fixed effects" and "Random effects"), with the effects indented below them. Headings are added only when random effects are displayed. The random-effects heading names the statistic of the SD (or variance) rows (e.g., "Random effects (SD)"), and each cluster (grouping factor) gets a subheading with its terms indented below it; correlation (or covariance) rows name their own statistic (e.g., "r (Constant, Days)"). Without headings, each random-effect label names its cluster and statistic (e.g., "Subject: SD (Days)").

random_scale

for mixed models, "sd" (default) displays random effects as standard deviations (SD) and correlations (r), and "variance" displays them as variances (Var) and covariances (Cov).

terms

for generalized additive models (mgcv::gam), which terms to show: "all" (default) for the parametric terms and the smooth terms under their own headings, "parametric", or "smooth"

ci

for quantile regression (quantreg::rq), lavaan, and generalized estimating equation (geepack::geeglm) models, the confidence level of the intervals shown when predictor_parameters includes "CI" (default .95). For other models, pass ci in ... to parameters::model_parameters().

correlation_rows

for generalized estimating equations (geepack::geeglm), whether the estimated parameters of the working correlation are shown below the coefficients. If NULL (default), they are shown when there is a single parameter (\alpha of exchangeable and AR(1) structures), and not for unstructured correlations, which have one for each pair of occasions.

standardize

for lavaan models, if TRUE (default), fully standardized estimates (\beta) are displayed with their standard errors and p-values. If FALSE, unstandardized estimates (B) are displayed.

variances, intercepts

for lavaan models, if TRUE, sections for (residual) variances or intercepts are added. Both are FALSE by default. (The variance argument of apa_loadings() is different: it adds rows for the variance explained by each factor.)

groups

for multiple-group lavaan models, "columns" (default) shows the groups side by side, each under a column spanner, and "rows" stacks them, each under a heading row.

studies

for meta-analyses (metafor::rma()), if TRUE, the table has a row for each study (its effect size, confidence interval, and weight) followed by the pooled estimate. If FALSE, the table has the model's coefficients (the pooled estimate, or the intercept and moderators of a meta-regression). If NULL (default), TRUE for models without moderators and FALSE for meta-regressions.

weights

for the study rows of meta-analyses, if TRUE (default), each study's percentage of the total weight is shown

transform

for meta-analyses, if TRUE (default), effect sizes computed on a transformed scale are shown on their original scale: log risk ratios, odds ratios, incidence rate ratios, and ratios of means are exponentiated, and Fisher's z-transformed correlations are converted back to correlations. In meta-regressions, exponentiated coefficients are added in a separate column. If FALSE, estimates stay on the scale on which they were analyzed.

outcomes

for multivariate linear models (lm(cbind(y1, y2) ~ x)), where each outcome's coefficients go: "rows" (default), under a heading row for each outcome, or "columns", side by side under a column spanner for each outcome.

category_headings

for multinomial models, if TRUE (default), the coefficients of each outcome category are introduced by a heading row that names the comparison (e.g., "Part time vs. Not working"), with the predictors indented below it. If FALSE, each row is labeled with its category and predictor (e.g., "Part time: Children").

se

for quantile regression models, the method of computing standard errors, passed to quantreg::summary.rq(): "nid" (default) for Hendricks-Koenker sandwich estimates, which allow the errors to differ across cases, "iid" for estimates that assume independent and identically distributed errors, "ker" for Powell kernel estimates, or "boot" for bootstrap estimates. (quantreg's own default for fewer than 1,000 cases, "rank", gives confidence intervals without standard errors.)

quantiles

for quantile regression models with several quantiles (quantreg::rq(tau = c(.25, .5, .75))), "columns" (default) to show each quantile's estimates side by side under a column spanner (e.g., "\tau = .25"), or "rows" to stack them under heading rows

performance_parameters

for lists of models, model comparison metrics passed to apa_performance_comparison(). If NULL, no metrics are added. By default, they depend on the kind of model and the layout (see Details): in rows (performance_layout = "rows"), each model's fit, its change, the test of the change (with its degrees of freedom in the label and its stars), and an information criterion; in columns, R2 and deltaR2 (and, for mixed models, R2_conditional and deltaR2_conditional, with R2 the marginal R^2^), except for models without a valid R^2^ or nested tests: R2, deltaR2, and AIC for GAMs, R1 and AIC for quantile regressions, Sigma_robust for rlm, and QIC for generalized estimating equations.

performance_layout

for lists of models, where the model comparison metrics go: "rows" (default) adds a row for each metric below the model's parameters (and random effects), labeled in the variable column (e.g., R^2^ and \Delta R^2) with its value in the first value column, as in many hierarchical regression tables, and metrics without a value (e.g., the change in R^2^ of the first model) are left out; "columns" (the default before apa7 0.3.0) adds a column for each metric, with its value on the model's heading row.

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 apa_parameters() accepts (except aov, aovlist, and afex_aov), or a named list of models

metrics

fit statistics to display, named as in performance::model_performance() (e.g., "R2", "R2_adjusted", "AIC", "BIC", "RMSE", "Sigma"). The defaults depend on the model: R2 and Sigma for lm; R2 (a pseudo-R^2^) and AIC for glm, ordinal, multinomial, zero-inflated, and hurdle models; R2_marginal, R2_conditional, and ICC for mixed models; R2_adjusted, Deviance_explained, and AIC for generalized additive models; and the fit indices listed under apa_performance.lavaan() for lavaan models. For meta-analyses and lists, NULL (default) chooses them.

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 NULL (default), R2, deltaR2, F, and p for models with an estimated dispersion parameter (e.g., lm, Gaussian or quasi-family glm), and R2, deltaR2, Chi2, df, and p for GLMs with a fixed dispersion parameter (binomial, Poisson, negative binomial). Use "all" for all available metrics.

starred

columns to which significance stars are added (e.g., "Coefficient" or "p"). NULL or NA for none.

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 metafor::rma() (without moderators)

methods

methods to display, in order: any of "egger", "rank", "trimfill", and "fsn"

transform

if TRUE (default), estimates computed on a transformed scale are shown on their original scale, as in apa_parameters()

Details

The methods (rows) are:

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., list(Agreeableness = c(A1, A2, A3), Conscientiousness = starts_with("C"))). A named list of character vectors stored in a variable works too. If NULL (default), all columns of data form one scale.

reverse

items to reverse-score before the analysis, selected like the items in scales (e.g., c(A1, C4, C5)). Items are reversed within their scale's range of responses (item_range), and they are marked "(R)" in the table.

item_range

lowest and highest possible responses, used to reverse items. If NULL (default), the lowest and highest responses observed in each scale are used.

level

"items" (default) for item rows followed by each scale's statistics, or "scales" for one row per scale.

omega

if TRUE (default), McDonald's \omega_{\text{total}} is shown

ci

confidence level of the interval of \alpha

score

"mean" (default) or "sum": how scale scores are computed

flag

NULL (default) or a number: item-total correlations below it, and \alpha-if-deleted values above the scale's \alpha, are bolded (e.g., flag = .30), and the note says so. TRUE is the same as .30. This works like flag in apa_collinearity().

format_variable_names

if TRUE (default), item and scale names are lightly formatted: underscores become spaces, and the first letter is capitalized (item codes such as "A1" stay intact). Set to FALSE to keep names exactly as they are.

digits

number of decimal places (unaffected by apa7_defaults(accuracy = ))

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

a flextable::flextable()

font_family

font family (e.g., "Times New Roman" or "Arial"). If NULL (default), the font set with apa7_defaults(font_family = ) (Times New Roman unless changed).

font_size

font size, in points. If NULL (default), the size set with apa7_defaults(font_size = ) (12 unless changed).

text_color

color of the text: an R color name (e.g., "black", the default) or a hex code (e.g., "#333333")

border_color

color of the rules, in the same forms as text_color

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 NULL (default), the spacing set with apa7_defaults(line_spacing = ) (2 unless changed). Table notes are single-spaced.

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: "left" (default), "center", or "right"

header_align_vertical

vertical alignment of header text when header cells differ in height: "top" (default), "middle", or "bottom"

layout

"autofit" (default) lets the column widths adjust to the contents in Word; "fixed" keeps the widths as set (see flextable::set_table_properties())

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 apa7_defaults(table_width = )), "page" (or "portrait") for the full width of a portrait page, "landscape" for a landscape page, "column" for one column of a two-column page, or a named number: a proportion of one of these widths (e.g., c(landscape = .8)) or a width in inches, cm, or mm (e.g., c(inches = 5)). With 0, the columns are only as wide as their contents need. If NULL (default), the width set by the code chunk's apa7-width option in Quarto (e.g., ⁠#| apa7-width: landscape⁠, or ⁠#| apa7-width: {landscape: .8}⁠ for a named number) or apa7.width option in R Markdown, or "page" for a chunk with apaquarto's apa-twocolumn: true; otherwise, the table_width set with apa7_defaults() (1 unless changed). The widths of the pages and the column are set with the page_width, landscape_width, and column_width arguments of apa7_defaults(). A number greater than 1 is read as inches, with a warning to write it as c(inches = ).

markdown

if TRUE (default), text in the header and body is converted from markdown (e.g., ⁠*p*⁠ becomes an italic p)

markdown_header, markdown_body

whether the header or the body is converted from markdown (both default to markdown)

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 no_markdown_columns.

separate_headers

if TRUE (default) and the table has one header row, column names with an underscore are split into a column spanner and a header (e.g., ⁠Model 1_B⁠ becomes "B" under a "Model 1" spanner)

Details

With a few minor details omitted, apa_style() does roughly this:

  1. Separates the headers into column spanners and deckered heads at underscores, if separate_headers = TRUE and the header has one row.

  2. Sets the font, font size, and text color of every cell.

  3. Draws the three horizontal rules of an APA table: above the header, below the header, and below the body.

  4. Top-aligns the body cells, centers the header text, and aligns the header cells vertically with header_align_vertical.

  5. 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 of line_spacing while 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 is horizontal_padding.

  6. Styles apa7's helper columns. Break columns (from add_break_columns()) are left empty. Star columns (from add_star_column() and separate_star_column()) and list columns (from add_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.

  7. Sets the table's layout, alignment on the page, and width (layout, table_align, and table_width). In Word, the table is kept on the same page as the text that follows it.

  8. Converts markdown in the header and the body with ftExtra::colformat_md(), except in the columns named in no_markdown_columns_header and no_markdown_columns and in cells that are already formatted.

  9. If the first column is named Variable or Predictor, 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 metafor::rma()

subgroup

the subgroup variable: the name of a column in the data of fit (quoted or unquoted), or a vector with one value for each effect size. Effect sizes whose subgroup is missing are left out of the subgroups (but not of the overall estimate).

tau2

"separate" (default) for a \tau^2 for each subgroup, or "common" for one \tau^2 shared by all subgroups

transform

if TRUE (default), estimates computed on a transformed scale are shown on their original scale, as in apa_parameters()

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 apa_note() to define the abbreviations in a table's note (e.g., "standardized coefficient" defines the ⁠&beta;⁠ header as "&beta; = standardized coefficient"). The term defined is the header, unless the string is named (e.g., c(CI = "confidence interval") defines "CI" for a header such as "95% CI"). Leave empty (the default) for symbols that need no definition, such as M, SD, t, and p.

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 column_format objects

accuracy

rounding accuracy of the formatters (e.g., .01 for two decimals). If NULL (default), the accuracy set with apa7_defaults().

labels

named character vector of variable labels, named by the variables (e.g., c(parental_income = "Parental Income", n_siblings = "Number of Siblings")), as in apa_descriptives() and apa_chisq(). Reserved for a future version, in which these labels will be the default labels of every table function. For now, they are stored in the labels property, and no table function uses them; pass labels to apa_descriptives() or apa_chisq() instead.

custom_columns

named list of column_format() objects that are added, or that replace the formats of the same name

variable_labels

deprecated; use labels, with the variables as the names and the labels as the values

intercept_text, starred_columns

deprecated, and never used. Set the label of the intercept row for all tables with apa7_defaults(intercept_text = ), and the columns that get stars with the starred argument of each table function.

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_names

getter for column names

get_headers

getter for column headers

get_latex

getter for column latex headers

get_formatters

getter for column formatters

get_header_rename

getter for column names with headers as names

get_header_rename_latex

getter for column names with latex headers as names

get_tibble

getter for tibble with column names, headers, latex headers, and formatters

get_abbreviations

getter 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 space characters that indent the second and later lines

width

maximum number of characters per line

space

indenting character. If NULL (default), a non-breaking space.

newline

text inserted at each line break (default: a markdown hard line break, a backslash followed by a newline)

whitespace_only

if TRUE, lines break only at spaces. If FALSE (default), they can also break after hyphens and slashes (see stringr::str_wrap()).

wrap_equal_width

if TRUE, lines are made roughly equal in width (see str_wrap_equal()). If FALSE (default), each line is filled up to width.

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 TRUE, Quarto installs the extension without asking you to confirm the download. If FALSE (default), it asks.

quiet

if TRUE, Quarto's messages and warnings are suppressed

quarto_args

character vector of other Quarto command-line arguments, appended to the ⁠quarto add⁠ command

ask

if TRUE (default), ask before installing missing R packages (quarto, ragg, and svglite). If FALSE, install them without asking.

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 TRUE, returns a logical vector for each element, otherwise returns a single logical value indicating if all elements are numeric-like (default: FALSE)

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 TRUE (default), ask before installing missing packages. If FALSE, install missing packages without asking.

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: "[" (default) for square brackets, "(" for parentheses, "|" for vertical bars (as for a determinant), or "" for none

include_names

if TRUE (default), the matrix's row and column names are displayed above and to the left of the matrix

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 = "&numsp;",
  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 ⁠&numsp;⁠ (figure space)

NA_value

value to replace NA

font_family

font in which to measure text widths. If NULL (default) or NA, or if the font is not installed, widths are counted in characters.

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

<tidy-select> A set of columns that uniquely identify each observation. Typically used when you have redundant variables, i.e. variables whose values are perfectly correlated with existing variables.

Defaults to all columns in data except for the columns specified through names_from and values_from. If a tidyselect expression is supplied, it will be evaluated on data after removing the columns specified through names_from and values_from.

id_expand

Should the values in the id_cols columns be expanded by expand() before pivoting? This results in more rows, the output will contain a complete expansion of all possible values in id_cols. Implicit factor levels that aren't represented in the data will become explicit. Additionally, the row values corresponding to the expanded id_cols will be sorted.

names_from, values_from

<tidy-select> A pair of arguments describing which column (or columns) to get the name of the output column (names_from), and which column (or columns) to get the cell values from (values_from).

If values_from contains multiple values, the value will be added to the front of the output column.

names_prefix

String added to the start of every variable name. This is particularly useful if names_from is a numeric vector and you want to create syntactic variable names.

names_sep

If names_from or values_from contains multiple variables, this will be used to join their values together into a single string to use as a column name.

names_sort

Should the column names be sorted? If FALSE, the default, column names are ordered by first appearance.

names_vary

"slowest" (default) to keep the columns of each names_from value together, or "fastest" to interleave them (see tidyr::pivot_wider())

names_expand

Should the values in the names_from columns be expanded by expand() before pivoting? This results in more columns, the output will contain column names corresponding to a complete expansion of all possible values in names_from. Implicit factor levels that aren't represented in the data will become explicit. Additionally, the column names will be sorted, identical to what names_sort would produce.

names_repair

What happens if the output has invalid column names? The default, "check_unique" is to error if the columns are duplicated. Use "minimal" to allow duplicates in the output, or "unique" to de-duplicated by adding numeric suffixes. See vctrs::vec_as_names() for more options.

values_fill

Optionally, a (scalar) value that specifies what each value should be filled in with when missing.

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 id_cols and names_from columns does not uniquely identify an observation.

This can be a named list if you want to apply different aggregations to different values_from columns.

unused_fn

Optionally, a function applied to summarize the values from the unused columns (i.e. columns not identified by id_cols, names_from, or values_from).

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.

id_cols must be supplied for unused_fn to be useful, since otherwise all unspecified columns will be considered id_cols.

This is similar to grouping by the id_cols then summarizing the unused columns using unused_fn.

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: ⁠in⁠, cm, or mm. A table_width greater than 1 (without a name) is read in this unit.

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 apa7_defaults(table_width = )), "page" (or "portrait") for the full width of a portrait page, "landscape" for a landscape page, "column" for one column of a two-column page, or a named number: a proportion of one of these widths (e.g., c(landscape = .8)) or a width in inches, cm, or mm (e.g., c(inches = 5)). With 0, the columns are only as wide as their contents need. If NULL (default), the width set by the code chunk's apa7-width option in Quarto (e.g., ⁠#| apa7-width: landscape⁠, or ⁠#| apa7-width: {landscape: .8}⁠ for a named number) or apa7.width option in R Markdown, or "page" for a chunk with apaquarto's apa-twocolumn: true; otherwise, the table_width set with apa7_defaults() (1 unless changed). The widths of the pages and the column are set with the page_width, landscape_width, and column_width arguments of apa7_defaults(). A number greater than 1 is read as inches, with a warning to write it as c(inches = ).

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:

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 lb or at or above ub are written in scientific notation (e.g., 2.46 × 10^7^); numbers between them are written as usual

align

if TRUE, the numbers are aligned on the decimal point with align_chr()

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 TRUE

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., ⁠<span>⁠ or ⁠**⁠

right_tag

closing tag. By default, the opening tag with < replaced by ⁠</⁠ (e.g., ⁠<span>⁠ becomes ⁠</span>⁠), so markdown tags such as ⁠**⁠ close with themselves.

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)