| Title: | Writing Documents in American Psychological Association Style, Seventh Edition |
|---|---|
| Description: | Create American Psychological Association Style, Seventh Edition documents. Format numbers and text consistent with APA style. Create tables that comply with APA style by extending 'flextable' functions. |
| Authors: | W. Joel Schneider [aut, cre, cph] (ORCID: <https://orcid.org/0000-0002-8393-5316>) |
| Maintainer: | W. Joel Schneider <[email protected]> |
| License: | CC0 |
| Version: | 0.2.0.9000 |
| Built: | 2026-11-22 08:53:58 UTC |
| Source: | https://github.com/wjschne/apa7 |
Add break columns
add_break_columns( d, ..., .before = FALSE, omit_first = FALSE, omit_last = FALSE )add_break_columns( d, ..., .before = FALSE, omit_first = FALSE, omit_last = FALSE )
d |
data.frame or tibble |
... |
Column name or tidyselect function. Select columns |
.before |
insert break columns before selected columns (defaults to FALSE) |
omit_first |
omit the first break column |
omit_last |
omit the last break column |
data.frame or tibble
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)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
add_list_column( data, ..., type = c("1", "a", "A", "I", "i"), sep = ". ", merge = FALSE )add_list_column( data, ..., type = c("1", "a", "A", "I", "i"), sep = ". ", merge = FALSE )
data |
data.frame or tibble |
... |
Column name or tidyselect function. Select columns. Default is first column |
type |
list type. Can be "1" (numeric), "a" (lowercase alphabetical), or "ABC" (uppercase alphabetical), "i" (lowercase Roman numerals), "I" (uppercase Roman numerals) |
sep |
separator |
merge |
If |
data.frame
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)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
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 = "\\" )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 = "\\" )
data |
data.frame or tibble |
... |
Column name or tidyselect function. Select columns |
p |
Column name or tidyselect function. Select p-value column name |
merge |
merge and balance columns (default: |
superscript |
make as superscript |
star |
text for making stars |
alpha |
vector of thresholds |
first_alpha_marginal |
if TRUE, the first alpha value is treated as marginal and gets a dagger instead of a star |
add_trailing_space |
if TRUE, adds a trailing space after the stars (default: FALSE) |
prefix |
usually backslashes to prevent markdown from interpreting asterisks as bullets or italics |
data.frame
data.frame(b = c(1.4,2.2), p = c(.54, .02)) |> add_star_column(b, p)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)
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, ... )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, ... )
x |
vector (numeric or character) |
accuracy |
number to round to. If NULL, the current default accuracy set with |
trim_leading_zeros |
if TRUE (default), trims leading zeros, otherwise keeps them |
drop0trailing |
Drop trailing zeros |
add_plusses |
if TRUE (default), adds a plus to positive numbers |
padding_character |
character to use for padding, default is |
center |
text on which to align text. Center on decimal by default, but can be any text. |
format_integers |
If TRUE, integers will be formatted with digits |
side |
side on which to make text of equal width |
NA_value |
value to replace NA |
format_numeric_character |
format character variables with numeric content |
... |
additional arguments passed to |
character vector
align_chr(c(1, 10, 100))align_chr(c(1, 10, 100))
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()).
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, ...)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, ...)
fit |
an |
anova_parameters |
columns to display. |
effect_size |
effect size to display: |
partial |
if |
generalized |
if |
type |
type of sums of squares for |
ci |
confidence level for the effect size interval, shown if |
residual_label |
label for residual (error) rows |
starred |
columns to star with significant p-values (e.g., |
bolded |
columns to bold, if significant |
column_formats |
column_formats object to format columns. If NULL, the default column_formats is used. |
... |
further arguments passed to |
ddf |
for linear mixed models, method of approximating the denominator degrees of freedom: |
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 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.
apa7_tbl (tibble)
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("lmerTest", quietly = TRUE) && requireNamespace("pbkrtest", quietly = TRUE)) { fit_lmer <- lme4::lmer( Reaction ~ Days + (Days | Subject), data = lme4::sleepstudy ) apa_anova(fit_lmer) }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("lmerTest", quietly = TRUE) && requireNamespace("pbkrtest", quietly = TRUE)) { fit_lmer <- lme4::lmer( Reaction ~ Days + (Days | Subject), data = lme4::sleepstudy ) apa_anova(fit_lmer) }
Make contingency table with chi-square test of independence
apa_chisq( data, note = NULL, row_title_column = NULL, row_title_prefix = "", row_title_sep = " ", row_title_align = "center", row_title_border = list(color = "gray20", style = "solid", width = 1), left_column_padding = 20, cwidth = 0.75, cheight = 0.25, separate_headers = TRUE, apa_style = TRUE, font_family = NULL, font_size = 12, text_color = "black", border_color = "black", border_width = 0.5, line_spacing = 2, horizontal_padding = 3, table_align = "left", layout = "autofit", table_width = 1, markdown = TRUE, markdown_header = markdown, markdown_body = markdown, auto_format_columns = TRUE, column_formats = NULL, pretty_widths = TRUE, suppress_warnings = TRUE, ... )apa_chisq( data, note = NULL, row_title_column = NULL, row_title_prefix = "", row_title_sep = " ", row_title_align = "center", row_title_border = list(color = "gray20", style = "solid", width = 1), left_column_padding = 20, cwidth = 0.75, cheight = 0.25, separate_headers = TRUE, apa_style = TRUE, font_family = NULL, font_size = 12, text_color = "black", border_color = "black", border_width = 0.5, line_spacing = 2, horizontal_padding = 3, table_align = "left", layout = "autofit", table_width = 1, markdown = TRUE, markdown_header = markdown, markdown_body = markdown, auto_format_columns = TRUE, column_formats = NULL, pretty_widths = TRUE, suppress_warnings = TRUE, ... )
data |
A two-column data.frame or tibble |
note |
Custom note (overrides automatic note.) |
row_title_column |
Column name or tidyselect function. column to group rows |
row_title_prefix |
text to be added to each title |
row_title_sep |
separator for prefix |
row_title_align |
alignment of row title ("left", "center", "right") |
row_title_border |
list of flextable styles |
left_column_padding |
Number of points the left column is padded (only relevant when there is a |
cwidth |
initial cell width in inches |
cheight |
initial cell height in inches |
separate_headers |
separate header rows (default: |
apa_style |
apply |
font_family |
font family |
font_size |
font size |
text_color |
text color |
border_color |
border color |
border_width |
border width in pixels |
line_spacing |
spacing between lines of the header and body. Table notes are single-spaced. |
horizontal_padding |
horizontal padding (in pixels) |
table_align |
table alignment ("left", "center", "right") |
layout |
table layout ("autofit", "fixed") |
table_width |
table width (in pixels, 0 for auto) |
markdown |
apply markdown formatting to header and body |
markdown_header |
apply markdown formatting to header |
markdown_body |
apply markdown formatting to body |
auto_format_columns |
if true, will attempt to format some columns automatically |
column_formats |
a column_formats object |
pretty_widths |
apply |
suppress_warnings |
Suppress any warnings if true. |
... |
arguments passed to |
flextable::flextable
apa_chisq(mtcars[, c("am", "gear")])apa_chisq(mtcars[, c("am", "gear")])
APA-formatted correlation table
apa_cor( data, note = NULL, p_value = c(0.05, 0.01, 0.001), digits = 2, bold_significant = FALSE, star_significant = TRUE, significance_note = TRUE, output = c("flextable", "tibble"), font_family = NULL, font_size = 12, text_color = "black", border_color = "black", border_width = 0.5, line_spacing = 2, table_width = 6.5, keep_empty_star_columns = TRUE, summary_functions = list(M = mean, SD = stats::sd), column_formats = NULL, ... )apa_cor( data, note = NULL, p_value = c(0.05, 0.01, 0.001), digits = 2, bold_significant = FALSE, star_significant = TRUE, significance_note = TRUE, output = c("flextable", "tibble"), font_family = NULL, font_size = 12, text_color = "black", border_color = "black", border_width = 0.5, line_spacing = 2, table_width = 6.5, keep_empty_star_columns = TRUE, summary_functions = list(M = mean, SD = stats::sd), column_formats = NULL, ... )
data |
data.frame or tibble with variables to be |
note |
Custom note to appear below table. (Overrides automatic note.) |
p_value |
p-value needed to be flagged as significant |
digits |
Number of digits for rounding |
bold_significant |
bold significant correlations |
star_significant |
start significant correlations |
significance_note |
If TRUE, place note at bottom of table that significant correlations are bolded. |
output |
output type. Can be "flextable" or "tibble" |
font_family |
font family |
font_size |
font size |
text_color |
text color |
border_color |
border color |
border_width |
border width in pixels |
line_spacing |
spacing between lines of the header and body. Table notes are single-spaced. |
table_width |
table width (in pixels, 0 for auto) |
keep_empty_star_columns |
Keep remove empty star columns (Default: |
summary_functions |
Any named list of functions that summarize data columns (e.g., |
column_formats |
column_formats object |
... |
< |
flextable::flextable
apa_cor(mtcars[, c("mpg", "am", "gear", "carb")]) apa_cor(mtcars[, c("mpg", "am", "gear", "carb")], output = "tibble", star_significant = FALSE)apa_cor(mtcars[, c("mpg", "am", "gear", "carb")]) apa_cor(mtcars[, c("mpg", "am", "gear", "carb")], output = "tibble", star_significant = FALSE)
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().
apa_factor_cor(fit, factor_names = NULL, digits = 2)apa_factor_cor(fit, factor_names = NULL, digits = 2)
fit |
a |
factor_names |
names for the factors. Either an unnamed character vector in the order the factors appear in the table (psych orders factors by variance explained), or a named vector that maps the original names to new names (e.g., |
digits |
number of decimal places |
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().
apa7_tbl (tibble)
fit <- psych::fa(Harman74.cor$cov, 4, fm = "pa", rotate = "oblimin") apa_factor_cor( fit, factor_names = c("Verbal", "Spatial", "Memory", "Speed") )fit <- psych::fa(Harman74.cor$cov, 4, fm = "pa", rotate = "oblimin") apa_factor_cor( fit, factor_names = c("Verbal", "Spatial", "Memory", "Speed") )
The apa_flextable function performs a number of formatting operations on the data before and after the data are sent to flextable. See Details.
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 = 12, text_color = "black", border_color = "black", border_width = 0.5, line_spacing = 2, horizontal_padding = 3, table_align = "left", layout = "autofit", table_width = 1, 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, ... )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 = 12, text_color = "black", border_color = "black", border_width = 0.5, line_spacing = 2, horizontal_padding = 3, table_align = "left", layout = "autofit", table_width = 1, 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, ... )
data |
data.frame or tibble |
row_title_column |
Column name or tidyselect function. column to group rows |
row_title_align |
alignment of row title ("left", "center", "right") |
row_title_prefix |
text to be added to each title |
row_title_sep |
separator for prefix |
row_title_border |
list of flextable styles |
left_column_padding |
Number of points the left column is padded (only relevant when there is a |
col_keys |
column keys passed to flextable (defaults data column names) |
cwidth |
initial cell width in inches |
cheight |
initial cell height in inches |
header_align_vertical |
vertical alignment of headers. Can be "top", "middle", or "bottom" |
separate_headers |
separate header rows (default: |
apa_style |
apply |
font_family |
font family |
font_size |
font size |
text_color |
text color |
border_color |
border color |
border_width |
border width in pixels |
line_spacing |
spacing between lines of the header and body. Table notes are single-spaced. |
horizontal_padding |
horizontal padding (in pixels) |
table_align |
table alignment ("left", "center", "right") |
layout |
table layout ("autofit", "fixed") |
table_width |
table width (in pixels, 0 for auto) |
markdown |
apply markdown formatting to header and body |
markdown_header |
apply markdown formatting to header |
markdown_body |
apply markdown formatting to body |
no_markdown_columns |
body columns that should not be treated as markdown |
no_markdown_columns_header |
column headers that should not be treated as markdown |
no_format_columns |
Column name or tidyselect function. selected columns are not formatted. Columns named in a |
auto_format_columns |
if true, will attempt to format some columns automatically |
column_formats |
a column_formats object |
pretty_widths |
apply |
add_breaks_between_spanners |
add breaks between spanners if TRUE |
note |
table note placed below the table, after "Note.". The note is single-spaced. If |
... |
arguments passed to |
Roughly speaking, apa_flextable performs these operations by default:
Apply as_grouped_data and restructure row titles, if row_title is specified.
Format data with apa_format_columns if auto_format_columns = TRUE
Separate headers into multiple header rows if separate_headers = TRUE
Apply flextable::flextable
Apply flextable::surround to make borders to separate row groups, if any.
Apply the apa_style function (table formatting and markdown conversion) if apa_style = TRUE
Apply pretty_widths if pretty_widths = TRUE
flextable::flextable
library(dplyr) library(tidyr) library(flextable) mtcars %>% dplyr::select(vs, am, gear, carb) |> tidyr::pivot_longer(-vs, names_to = "Variable") |> dplyr::summarise(Mean = round(mean(value), 2), SD = round(sd(value), 2), .by = c(Variable,vs)) |> dplyr::mutate(vs = factor(vs, levels = 0:1, labels = c("Automatic", "Manual"))) |> apa_flextable(row_title_column= vs, row_title_align = "center") |> align(j = 2:3, align = "center")library(dplyr) library(tidyr) library(flextable) mtcars %>% dplyr::select(vs, am, gear, carb) |> tidyr::pivot_longer(-vs, names_to = "Variable") |> dplyr::summarise(Mean = round(mean(value), 2), SD = round(sd(value), 2), .by = c(Variable,vs)) |> dplyr::mutate(vs = factor(vs, levels = 0:1, labels = c("Automatic", "Manual"))) |> apa_flextable(row_title_column= vs, row_title_align = "center") |> align(j = 2:3, align = "center")
Format data columns
apa_format_columns( data, column_formats = NULL, no_format_columns = NULL, rename_headers = TRUE, latex_headers = FALSE, format_separated_headers = TRUE, sep = "_", accuracy = NULL )apa_format_columns( data, column_formats = NULL, no_format_columns = NULL, rename_headers = TRUE, latex_headers = FALSE, format_separated_headers = TRUE, sep = "_", accuracy = NULL )
data |
data set (data.frame or tibble) |
column_formats |
|
no_format_columns |
Column name or tidyselect function. selected columns are not formatted |
rename_headers |
if |
latex_headers |
if |
format_separated_headers |
if |
sep |
separator for separated headers (default is "_") |
accuracy |
numeric (default: NULL, uses the current default accuracy set with |
tibble
lm(mpg ~ cyl + wt, data = mtcars) |> parameters::parameters() |> apa_format_columns() |> apa_flextable()lm(mpg ~ cyl + wt, data = mtcars) |> parameters::parameters() |> apa_format_columns() |> apa_flextable()
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()).
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, ... )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, ... )
data |
data frame |
formula |
two-sided formula with outcome variables on the left and a
grouping or predictor variable on the right. Several outcomes are joined
with |
test |
type of test:
|
effect_size |
effect size to display. If For paired t tests, Cohen's d is d~av~ ( |
ci |
confidence level of the effect size interval (for correlation tests, the interval of Pearson's r). Intervals are two-sided. |
var_equal |
if |
mu |
value that one-sample tests compare each variable with (for two-group tests, the hypothesized difference in location) |
method |
correlation coefficient: |
descriptives |
if |
pair_labels |
for paired tests, labels of the first and second
variable of each pair, used as the headings above their descriptive
statistics (e.g., |
starred |
columns to star with significant p-values (e.g., |
bolded |
columns to bold, if significant |
column_formats |
column_formats object to format columns. If NULL, the default column_formats is used. |
... |
further arguments passed to the test function (e.g.,
|
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.
apa7_tbl (tibble)
# 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)# 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)
Makes an APA-style table of factor loadings from an exploratory factor analysis or a principal components analysis.
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 )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 )
fit |
a |
sort_loading |
sort the rows so that variables are grouped by the factor with their largest loading, and by the size of that loading within each factor (as in |
min_loading |
minimum absolute loading to display. Use |
factor_names |
names for the factors. Either an unnamed character vector in the order the factors appear in the table (psych orders factors by variance explained), or a named vector that maps the original names to new names (e.g., |
variance |
add rows for the variance explained by each factor |
communality |
add a communality (h^2^) column |
uniqueness |
add a uniqueness (u^2^) column |
complexity |
add a column with Hofmann's complexity index |
bold_max |
bold the largest displayed loading (in absolute value) in each row |
format_variable_names |
format the variable names with the |
digits |
number of decimal places for loadings |
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).
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.
apa7_tbl (tibble)
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()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()
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.
apa_note(x, collapse = " ")apa_note(x, collapse = " ")
x |
a table made by |
collapse |
string that joins the sentences. Use |
For apa_anova() tables, the note can say
which type of sums of squares was used,
which effects have sphericity-corrected degrees of freedom (for afex
models, only effects involving a within-subjects factor with more than
two levels are corrected),
what the effect size (and MSE, for afex models) stands for, and
what stars or bold values mean.
For apa_loadings() tables, the note can say
how the factors were extracted and rotated (e.g., "Principal axis factoring with oblimin rotation"), and that loadings after an oblique rotation are pattern coefficients,
which loadings are omitted (min_loading) or bolded (bold_max),
what the h^2^, u^2^, and Complexity columns stand for, and
that the cumulative proportion of variance is approximate when the factors are correlated.
For apa_factor_cor() tables, the note says how the factors were
extracted and rotated.
For apa_htest() tables, the note can say
which tests were done (e.g., Welch's t tests) and what the groups were compared with or the variables were correlated with,
that p-values are one-sided, if they are,
how Cohen's d (or Hedges' g) was standardized,
what the effect size and its confidence interval stand for, and
what stars or bold values mean.
For apa_parameters() tables of regression models (lm, glm, polr,
clm, lme4, glmmTMB, and nlme models, or a list of models), the note can say
which robust standard errors were used (e.g., vcov = "HC3"),
how the degrees of freedom of mixed-model t tests were approximated (Kenward-Roger or Satterthwaite),
that ordinal-model thresholds are not tested,
the scale of the zero-inflation and dispersion coefficients of glmmTMB
models,
the residual correlation structure and variance function of nlme::lme
models,
what the standardized coefficient (), exponentiated coefficient
(e.g., OR), confidence interval, and model-comparison (e.g.,
) columns stand for, and
what stars or bold values mean.
Abbreviations are defined from the abbreviation slot of each column's
column_format(), so a note defines every abbreviated header that has a
definition. To define another header, or to change a definition, set the
slot in the column_formats passed to the table function (or set the
default with apa7_defaults()):
cf <- column_formats()
cf$Sum_Squares@abbreviation <- "sum of squares"
apa_anova(fit, anova_parameters = c("Parameter", "Sum_Squares", "df", "F", "p"),
column_formats = cf)
The sentences are in APA order: general notes first, then probability notes.
The text does not start with "Note." because apaquarto adds it. With
apaquarto, make the table in one
chunk and display it in another, using the note as the apa-note chunk
option. Write apa7::apa_note() there, because in documents with cached
chunks, chunk options can be evaluated before library(apa7) takes effect:
```{r}
#| label: anova-fit
tbl <- apa_anova(fit, type = 3)
```
```{r}
#| label: tbl-anova
#| tbl-cap: Analysis of Variance
#| apa-note: !expr apa7::apa_note(tbl)
tbl
```
The information is stored in an "apa_note" attribute of the table. dplyr
functions such as mutate() and filter() keep it, but some operations
(e.g., bind_rows() and joins) drop it, so call apa_note() on the
table that the table function returned.
character
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) 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_note(apa_anova(fit_afex)) } # 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()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) 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_note(apa_anova(fit_afex)) } # 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
apa_p( p, inline = FALSE, markdown = TRUE, min_digits = 2, max_digits = 3, align = FALSE )apa_p( p, inline = FALSE, markdown = TRUE, min_digits = 2, max_digits = 3, align = FALSE )
p |
probability |
inline |
If TRUE (default), returns statistic (e.g., p = .04), otherwise just the number (e.g., .04) |
markdown |
By default, outputs text compatible with markdown if TRUE, otherwise prints plain text compatible with 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 |
character vector
# 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)# 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
apa_p_star_note(x = c(0.05, 0.01, 0.001), first_alpha_marginal = FALSE)apa_p_star_note(x = c(0.05, 0.01, 0.001), first_alpha_marginal = FALSE)
x |
vector of alpha values (p-value thresholds) |
first_alpha_marginal |
if TRUE, the first alpha value is treated as marginal and gets a dagger instead of a star |
character vector
apa_p_star_note() apa_p_star_note(x = c(0.10, 0.05, 0.01, 0.001), first_alpha_marginal = TRUE)apa_p_star_note() apa_p_star_note(x = c(0.10, 0.05, 0.01, 0.001), first_alpha_marginal = TRUE)
format model parameters in APA style
## 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 '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, ... ) apa_parameters( fit, predictor_parameters = c("Coefficient", "SE", "Std_Coefficient", "t", "df_error", "p"), starred = NULL, bolded = NULL, column_formats = NULL, t_with_df = TRUE, ... ) ## 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 '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 '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, ... ) ## 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, ... ) ## 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, ... ) ## 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"), ... )## 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 '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, ... ) apa_parameters( fit, predictor_parameters = c("Coefficient", "SE", "Std_Coefficient", "t", "df_error", "p"), starred = NULL, bolded = NULL, column_formats = NULL, t_with_df = TRUE, ... ) ## 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 '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 '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, ... ) ## 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, ... ) ## 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, ... ) ## 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"), ... )
fit |
model fit object |
predictor_parameters |
predictor parameters to display. If named vector, column names will be vector names. Columns not present in the model output (e.g., |
starred |
columns to star with significant p_values |
bolded |
columns to bold, if significant |
column_formats |
column_formats object to format columns. If NULL, the default column_formats is used. |
t_with_df |
if TRUE, the t column will be displayed with degrees of freedom in parentheses. If FALSE, only the t value is displayed. |
... |
arguments passed to methods. For |
standardize |
for |
variances, intercepts
|
for |
thresholds |
for ordinal models, if |
ci |
for |
exponentiate |
if |
random |
for mixed models, if |
performance_parameters |
for lists of models, model comparison metrics passed to |
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 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 x1), "Regressions" (e.g., Speed Visual), "Correlations" (or "Covariances", if unstandardized; e.g., Visual 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. Multiple-group models are not yet supported.
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 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), labeled by grouping factor.
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.
tibble
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() } 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() } glm(am ~ wt + hp, data = mtcars, family = binomial) |> apa_parameters() |> apa_flextable() 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() }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() } 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() } glm(am ~ wt + hp, data = mtcars, family = binomial) |> apa_parameters() |> apa_flextable() 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 comparison metrics in APA style
apa_performance_comparison( ..., metrics = NULL, starred = NA, column_formats = NULL )apa_performance_comparison( ..., metrics = NULL, starred = NA, column_formats = NULL )
... |
model fit objects, or a list of them. Models are labeled by the list's names (or the argument names), and "Model 1", "Model 2", ... for unnamed models. |
metrics |
performance metrics. If |
starred |
columns to star with significant p_values |
column_formats |
column_formats object to format columns. If NULL, the default column_formats is used. |
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~).
Mixed models (lme4::lmer and lme4::glmer) 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^.
tibble
m1 <- lm(mpg ~ cyl, data = mtcars) m2 <- lm(mpg ~ cyl + wt, data = mtcars) apa_performance_comparison(list(`Model 1` =m1, `Model 3` =m2)) |> apa_flextable()m1 <- lm(mpg ~ cyl, data = mtcars) m2 <- lm(mpg ~ cyl + wt, data = mtcars) apa_performance_comparison(list(`Model 1` =m1, `Model 3` =m2)) |> apa_flextable()
Fit indices of lavaan models
format model performance metrics in APA style
## S3 method for class 'lavaan' apa_performance( fit, metrics = c("Chi2", "Chi2_df", "p_Chi2", "CFI", "TLI", "RMSEA", "RMSEA_CI", "SRMR"), column_formats = NULL ) apa_performance(fit, metrics = c("R2", "Sigma"), 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)## S3 method for class 'lavaan' apa_performance( fit, metrics = c("Chi2", "Chi2_df", "p_Chi2", "CFI", "TLI", "RMSEA", "RMSEA_CI", "SRMR"), column_formats = NULL ) apa_performance(fit, metrics = c("R2", "Sigma"), 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)
fit |
model fit object |
metrics |
performance metrics. Default is R2 and Sigma |
column_formats |
column_formats object to format columns. If NULL, the default column_formats is used. |
For structural equation models and confirmatory factor analyses fit with
lavaan (e.g., lavaan::cfa() or lavaan::sem()), the default metrics
are the model 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 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 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.
tibble
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) } lm(mpg ~ cyl + wt, data = mtcars) |> apa_performance() |> apa_flextable() list( `Cylinders` = lm(mpg ~ cyl, data = mtcars), `Cylinders and weight` = lm(mpg ~ cyl + wt, data = mtcars) ) |> apa_performance()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) } lm(mpg ~ cyl + wt, data = mtcars) |> apa_performance() |> apa_flextable() list( `Cylinders` = lm(mpg ~ cyl, data = mtcars), `Cylinders and weight` = lm(mpg ~ cyl + wt, data = mtcars) ) |> apa_performance()
flextable::flextable object according to APA styleStyle flextable::flextable object according to APA style
apa_style( x, font_family = NULL, font_size = 12, text_color = "black", border_color = "black", border_width = 0.5, line_spacing = 2, horizontal_padding = 3, table_align = "left", header_align_vertical = c("top", "middle", "bottom"), layout = "autofit", table_width = 0, markdown = TRUE, markdown_header = markdown, markdown_body = markdown, no_markdown_columns = NULL, no_markdown_columns_header = no_markdown_columns, separate_headers = TRUE )apa_style( x, font_family = NULL, font_size = 12, text_color = "black", border_color = "black", border_width = 0.5, line_spacing = 2, horizontal_padding = 3, table_align = "left", header_align_vertical = c("top", "middle", "bottom"), layout = "autofit", table_width = 0, markdown = TRUE, markdown_header = markdown, markdown_body = markdown, no_markdown_columns = NULL, no_markdown_columns_header = no_markdown_columns, separate_headers = TRUE )
x |
object |
font_family |
font family |
font_size |
font size |
text_color |
text color |
border_color |
border color |
border_width |
border width in pixels |
line_spacing |
spacing between lines of the header and body. Table notes are single-spaced. |
horizontal_padding |
horizontal padding (in pixels) |
table_align |
table alignment ("left", "center", "right") |
header_align_vertical |
vertical alignment of headers. Can be "top", "middle", or "bottom" |
layout |
table layout ("autofit", "fixed") |
table_width |
table width (in pixels, 0 for auto) |
markdown |
apply markdown formatting to header and body |
markdown_header |
apply markdown formatting to header |
markdown_body |
apply markdown formatting to body |
no_markdown_columns |
body columns that should not be treated as markdown |
no_markdown_columns_header |
column headers that should not be treated as markdown |
separate_headers |
separate headers into column spanner labels |
object
d <- data.frame(x = 1:3, y = 4:6) flextable::flextable(d) |> apa_style()d <- data.frame(x = 1:3, y = 4:6) flextable::flextable(d) |> apa_style()
Set defaults for apa7 package
apa7_defaults( accuracy = NULL, font_family = NULL, intercept_text = NULL, column_formats = NULL, number_formatter = NULL, trim_leading_zero = NULL, width_aware_padding = NULL, reset = FALSE )apa7_defaults( accuracy = NULL, font_family = NULL, intercept_text = NULL, column_formats = NULL, number_formatter = NULL, trim_leading_zero = NULL, width_aware_padding = NULL, reset = FALSE )
accuracy |
numeric (default: .01) |
font_family |
font family |
intercept_text |
what to call the intercept |
column_formats |
column formatting functions |
number_formatter |
default function to format numbers |
trim_leading_zero |
default function to trim leading zeros from numbers |
width_aware_padding |
if |
reset |
if |
previous defaults
apa7_defaults(accuracy = .001) # Reset to package defaults apa7_defaults(reset = TRUE)apa7_defaults(accuracy = .001) # Reset to package defaults apa7_defaults(reset = TRUE)
apa_flextable
The tibbles returned by apa_anova(), apa_factor_cor(), apa_htest(), apa_loadings(), apa_parameters(),
apa_performance(), and apa_performance_comparison() 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.
## S3 method for class 'apa7_tbl' print(x, ...) ## S3 method for class 'apa7_tbl' knit_print(x, ...)## S3 method for class 'apa7_tbl' print(x, ...) ## S3 method for class 'apa7_tbl' knit_print(x, ...)
x |
an |
... |
arguments passed to the next method |
The apa7.print option controls this behavior:
"auto" (default): flextable in knitr/Quarto, tibble in the console.
"flextable": flextable everywhere.
"tibble": tibble everywhere.
To render with non-default settings, pass the table to apa_flextable()
explicitly, which always returns a flextable.
x, invisibly, for print. A knit_asis or flextable output for knit_print.
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()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()
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.
column_format( name = character(0), header = character(0), latex = character(0), formatter = function() NULL, abbreviation = character(0) )column_format( name = character(0), header = character(0), latex = character(0), formatter = function() NULL, abbreviation = character(0) )
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 |
column_format object
R2 <- column_format( "R2", header = "*R*^2^", latex = "$R^2$", formatter = \(x, accuracy = the$accuracy, ...) { align_chr(x, accuracy = accuracy, trim_leading_zeros = TRUE, ...) }) R2 R2@header R2@formatter # Define an abbreviation in table notes SS <- column_formats()$Sum_Squares SS@abbreviation <- "sum of squares"R2 <- column_format( "R2", header = "*R*^2^", latex = "$R^2$", formatter = \(x, accuracy = the$accuracy, ...) { align_chr(x, accuracy = accuracy, trim_leading_zeros = TRUE, ...) }) R2 R2@header R2@formatter # Define an abbreviation in table notes SS <- column_formats()$Sum_Squares SS@abbreviation <- "sum of squares"
Returns an S7 object that contains a list of column_format objects that can be used to format parameters in APA style.
column_formats( .data = NULL, accuracy = NULL, intercept_text = NULL, starred_columns = character(0), variable_labels = character(0), custom_columns = NULL )column_formats( .data = NULL, accuracy = NULL, intercept_text = NULL, starred_columns = character(0), variable_labels = character(0), custom_columns = NULL )
.data |
list of |
accuracy |
numeric (passed to scales::number) |
intercept_text |
describe intercept |
starred_columns |
which columns get p-value stars |
variable_labels |
named vector of variable names (with vector names as labels). For example, c( |
custom_columns |
named list of column_formats to add or replace existing columns |
column_formats
get_column_namesgetter for column names
get_headersgetter for column headers
get_latexgetter for column latex headers
get_formattersgetter for column formatters
get_header_renamegetter for column names with headers as names
get_header_rename_latexgetter for column names with latex headers as names
get_tibblegetter for tibble with column names, headers, latex headers, and formatters
get_abbreviationsgetter for the abbreviations defined by the column formats, as a character vector of definitions named by the term defined
my_formatter <- column_formats() my_formatter$Coefficient@formatter <- \(x) round(x, 2) my_formatter$Coefficient@formatter(2.214)my_formatter <- column_formats() my_formatter$Coefficient@formatter <- \(x) round(x, 2) my_formatter$Coefficient@formatter(2.214)
Prepend column spanner labels to data column labels
column_spanner_label(data, label, ..., relocate = TRUE)column_spanner_label(data, label, ..., relocate = TRUE)
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 |
data.frame or tibble
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))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
hanging_indent( x, indent = 4, width = 30, space = NULL, newline = "\\\\\n", whitespace_only = FALSE, wrap_equal_width = FALSE )hanging_indent( x, indent = 4, width = 30, space = NULL, newline = "\\\\\n", whitespace_only = FALSE, wrap_equal_width = FALSE )
x |
text |
indent |
number of spaces to indent |
width |
number of characters to break lines |
space |
indenting space character (defaults to non-breaking space) |
newline |
text for creating new line |
whitespace_only |
wrapping spaces only |
wrap_equal_width |
Attempts to split lines to make them of approximately equal width |
character vector
hanging_indent("Hello Darkness, my old friend. I've come to talk with you again.")hanging_indent("Hello Darkness, my old friend. I've come to talk with you again.")
A wrapper for quarto::quarto_add_extension
install_apaquarto( no_prompt = FALSE, quiet = FALSE, quarto_args = NULL, ask = TRUE )install_apaquarto( no_prompt = FALSE, quiet = FALSE, quarto_args = NULL, ask = TRUE )
no_prompt |
Do not prompt to confirm approval to download external extension. |
quiet |
Suppress warning and other messages |
quarto_args |
Character vector of other quarto CLI arguments to append to the Quarto command executed by this function. |
ask |
if |
installs the apaquarto Quarto extension
## Not run: install_apaquarto() ## End(Not run)## Not run: install_apaquarto() ## End(Not run)
Tests if a character vector contains numeric-like values
is_numeric_like(x, elementwise = FALSE)is_numeric_like(x, elementwise = FALSE)
x |
character vector |
elementwise |
if |
logical vector
is_numeric_like(c("-9", " 2.0", "-1.0 ")) is_numeric_like(c("9-", -1, "10")) is_numeric_like(c("9", -1.2, "10"))is_numeric_like(c("-9", " 2.0", "-1.0 ")) is_numeric_like(c("9-", -1, "10")) is_numeric_like(c("9", -1.2, "10"))
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
make_apaquarto(launch.browser = TRUE, ask = TRUE)make_apaquarto(launch.browser = TRUE, ask = TRUE)
launch.browser |
run shiny app in default browser |
ask |
if |
Runs a shiny app that creates apaquarto documents
## Not run: make_apaquarto() ## End(Not run)## Not run: make_apaquarto() ## End(Not run)
Display latex matrices
matrix_display(x, bracket = c("[", "(", "|", ""), include_names = TRUE)matrix_display(x, bracket = c("[", "(", "|", ""), include_names = TRUE)
x |
a matrix |
bracket |
type of bracket: bmatrix, Bmatrix, pmatrix, vmatrix, Vmatrix, , matrix |
include_names |
if |
character
matrix_display(diag(2))matrix_display(diag(2))
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.
num_pad( x, pad_left = TRUE, padding_character = " ", NA_value = "", font_family = NULL )num_pad( x, pad_left = TRUE, padding_character = " ", NA_value = "", font_family = NULL )
x |
vector of text |
pad_left |
if TRUE (default), pads on the left, otherwise pads on the right |
padding_character |
character to use for padding, default is |
NA_value |
value to replace NA |
font_family |
font in which to measure text widths. If |
character vector
num_pad(c("a", "bb")) num_pad(c(paste0(intToUtf8(8722), "1"), "1"), font_family = "Times New Roman")num_pad(c("a", "bb")) num_pad(c(paste0(intToUtf8(8722), "1"), "1"), font_family = "Times New Roman")
Convert p-values to stars
p2stars( p, alpha = c(0.05, 0.01, 0.001), first_alpha_marginal = FALSE, superscript = FALSE, add_trailing_space = FALSE, prefix = "\\" )p2stars( p, alpha = c(0.05, 0.01, 0.001), first_alpha_marginal = FALSE, superscript = FALSE, add_trailing_space = FALSE, prefix = "\\" )
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 |
character vector
p2stars(c(.32, .02, .005), alpha = c(.05, .01))p2stars(c(.32, .02, .005), alpha = c(.05, .01))
name_variable instead of variable_name
The default for names_vary is "slowest" instead of the usual "fastest".
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 )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 )
data |
A data frame to pivot. |
... |
Additional arguments passed on to methods. |
id_cols |
< Defaults to all columns in |
id_expand |
Should the values in the |
names_from, values_from
|
< If |
names_prefix |
String added to the start of every variable name. This is
particularly useful if |
names_sep |
If |
names_sort |
Should the column names be sorted? If |
names_vary |
When
|
names_expand |
Should the values in the |
names_repair |
What happens if the output has invalid column names?
The default, |
values_fill |
Optionally, a (scalar) value that specifies what each
This can be a named list if you want to apply different fill values to different value columns. |
values_fn |
Optionally, a function applied to the value in each cell
in the output. You will typically use this when the combination of
This can be a named list if you want to apply different aggregations
to different |
unused_fn |
Optionally, a function applied to summarize the values from
the unused columns (i.e. columns not identified by The default drops all unused columns from the result. This can be a named list if you want to apply different aggregations to different unused columns.
This is similar to grouping by the |
data.frame
d <- data.frame(Model = paste0("Model","_", 1:2), t = 1:2, p = c(.05, .45)) pivot_wider_name_first(d, names_from = Model, values_from = c(t, p)) # For comparison: tidyr::pivot_wider(d, names_from = Model, values_from = c(t, p))d <- data.frame(Model = paste0("Model","_", 1:2), t = 1:2, p = c(.05, .45)) pivot_wider_name_first(d, names_from = Model, values_from = c(t, p)) # For comparison: tidyr::pivot_wider(d, names_from = Model, values_from = c(t, p))
Use flextable::dim_pretty to fit column widths
pretty_widths( x, min_width = 0.05, unit = c("in", "cm", "mm"), table_width = 6.5 )pretty_widths( x, min_width = 0.05, unit = c("in", "cm", "mm"), table_width = 6.5 )
x |
flextable |
min_width |
minimum width of columns |
unit |
Can be |
table_width |
width of table |
flextable::flextable
Scientific notation for markdown
sci_md(x, digits = 2, lb = 0.0095, ub = 99.5, align = FALSE)sci_md(x, digits = 2, lb = 0.0095, ub = 99.5, align = FALSE)
x |
Numeric vector |
digits |
number of digits of precision |
lb |
lower bound where scientific notation is turned on |
ub |
upper bound where scientific notation is turned on |
align |
decimal align |
A character vector
sci_md(c(.0045,1.44, 24567857.45))sci_md(c(.0045,1.44, 24567857.45))
Add columns that separate significance stars from numbers
separate_star_column( data, ..., superscript = TRUE, star = "\\*", star_replace = "\\\\*" )separate_star_column( data, ..., superscript = TRUE, star = "\\*", star_replace = "\\\\*" )
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: "\\*") |
data.frame or tibble
tibble::tibble(x = c(".45", ".58*", ".68**"), y = c(1,2,3), z = 4:6) |> separate_star_column(x)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
star_balance(x, star = "\\*", superscript = TRUE)star_balance(x, star = "\\*", superscript = TRUE)
x |
character vector |
star |
star text |
superscript |
Place superscript text if |
character vector
star_balance(".05\\^\\*\\*\\^")star_balance(".05\\^\\*\\*\\^")
stringr::str_wrap, but attempts to create lines of equal widthLike stringr::str_wrap, but attempts to create lines of equal width
str_wrap_equal(x, max_width = 30L, sep = "\n")str_wrap_equal(x, max_width = 30L, sep = "\n")
x |
character |
max_width |
maximum line width |
sep |
separation character |
character
str_wrap_equal("This function attempts to split the string into lines with roughly equal width.")str_wrap_equal("This function attempts to split the string into lines with roughly equal width.")
Surrounds text with tags unless empty
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)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)
x |
character vector |
tag |
opening tag, e.g., |
right_tag |
closing tag, e.g., |
level |
heading level |
character vector
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)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)