table_categorical() builds publication-ready categorical
tables for reports and articles in social science and data science
research. With by, it produces grouped cross-tabulation
tables with \(p\)-values from the
chi-squared or Fisher’s exact test, effect sizes, confidence intervals,
and multi-level headers. Without by, it produces one-way
frequency-style tables for the selected variables. Export to gt,
tinytable, flextable, Excel, or Word. Formatting follows APA conventions
by default; style = "jama" (or "nejm",
"lancet", "annals", "aer")
switches the whole table to that journal’s published rules — the
House styles section of Summary tables for
reporting shows each style and the guideline sentence behind
every rule. This article walks through the main features.
Basic usage
For grouped tables, provide a data frame, one or more selected variables, and a grouping variable:
table_categorical(
sochealth,
select = c(smoking, physical_activity, dentist_12m),
by = education
)
#> Categorical table by education
#>
#> Lower secondary Upper secondary Tertiary Total
#> ─────────────── ─────────────── ───────── ─────────
#> Variable │ n % n % n % n %
#> ───────────────────┼────────────────────────────────────────────────────────
#> smoking │
#> No │ 179 69.6 415 78.7 332 84.9 926 78.8
#> Yes │ 78 30.4 112 21.3 59 15.1 249 21.2
#> (Missing) │ 4 12 9 25
#> ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌
#> physical_activity │
#> No │ 177 67.8 310 57.5 163 40.8 650 54.2
#> Yes │ 84 32.2 229 42.5 237 59.2 550 45.8
#> ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌
#> dentist_12m │
#> No │ 113 43.3 174 32.3 67 16.8 354 29.5
#> Yes │ 148 56.7 365 67.7 333 83.2 846 70.5
#>
#> Variable │ p V
#> ───────────────────┼────────────
#> smoking │ <.001 .14
#> No │
#> Yes │
#> (Missing) │
#> ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌
#> physical_activity │ <.001 .21
#> No │
#> Yes │
#> ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌
#> dentist_12m │ <.001 .22
#> No │
#> Yes │
#>
#> Note. N = 1200: Lower secondary (n = 261), Upper secondary (n = 539), Tertiary (n = 400). Percentages are column percentages. P-values: Pearson chi-squared test. V = Cramér's V.The default output is "default", which prints a styled
ASCII table to the console, folded into successive panels when it is
wider than the console. Reading the table: each level of by
gets a pair of columns, the count n and the column
percentage computed within that group – percentages sum to 100
down each education group (for smoking within “Lower secondary”: 69.6 +
30.4 = 100.0, the four missing answers counted in their own row, out of
the base) – and the Total pair is the margin over all
groups combined. The note opens with the sample size and the size of
each group, then says the direction of the percentages. In the last
panel, p is the p-value of the test of association
between the row variable and by, computed once per variable
on its full cross-table (Pearson’s chi-squared here, as the note says;
see the test section below), and the final column is the association
measure – here Cramér’s V (covered below). Use
output = "data.frame" for a plain data frame suitable for
further processing.
percent = "row" reads the table the other way: each cell
is the share of the row’s respondents that falls in the group, so the
percentages sum to 100 across each row and the Total column
shows 100. total_row = TRUE closes the block with a Total
row, the share of each group overall, the base rate the rows are
compared with. With smoking as by, 29.9% of the respondents
with lower secondary education smoke and 14.8% of those with tertiary
education, against 20.8% overall. Only the percentages change: the
counts, the test and the association measure are those of the column
direction, and the note says the percentages are row percentages.
table_categorical(
sochealth,
select = education,
by = smoking,
percent = "row",
total_row = TRUE
)
#> Categorical table by smoking
#>
#> No Yes (Missing) Total
#> ───────── ───────── ───────── ───────────
#> Variable │ n % n % n % n % p V
#> ───────────────────┼──────────────────────────────────────────────────────────
#> education │ <.001 .14
#> Lower secondary │ 179 68.6 78 29.9 4 1.5 261 100.0
#> Upper secondary │ 415 77.0 112 20.8 12 2.2 539 100.0
#> Tertiary │ 332 83.0 59 14.8 9 2.2 400 100.0
#> ───────────────────┼──────────────────────────────────────────────────────────
#> Total │ 926 77.2 249 20.8 25 2.1 1200 100.0
#>
#> Note. N = 1200: No (n = 926), Yes (n = 249), (Missing) (n = 25). Percentages are row percentages. P-value: Pearson chi-squared test. V = Cramér's V.One-way tables
Omit by to build a frequency-style table for the
selected variables:
table_categorical(
sochealth,
select = c(smoking, physical_activity)
)
#> Categorical table
#>
#> Variable │ n %
#> ─────────────────────┼───────────────
#> smoking │
#> No │ 926 78.8
#> Yes │ 249 21.2
#> (Missing) │ 25
#> ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌
#> physical_activity │
#> No │ 650 54.2
#> Yes │ 550 45.8
#>
#> Note. N = 1200.select itself is optional: when omitted, the table
includes every eligible categorical column in the data – factor,
character, logical, and labelled (haven) columns – excluding the
by column, mirroring the select-less defaults of
table_continuous() and table_continuous_lm().
An explicit select is taken verbatim, so numeric-coded
categorical variables can still be tabulated by naming them.
Output formats
table_categorical() supports several output formats. The
table below summarizes the options:
| Format | Description |
|---|---|
"default" |
Styled ASCII table in the console (default) |
"data.frame" |
The displayed table, with its numbers |
"long" |
Long data frame, one row per level x group |
"gt" |
Formatted gt table |
"tinytable" |
Formatted tinytable |
"flextable" |
Formatted flextable |
"excel" |
Excel file (requires excel_path) |
"clipboard" |
Copy to clipboard |
"word" |
Word document (requires word_path) |
The three rendered formats ("gt",
"tinytable", "flextable") are demonstrated in
the final section, together with the file exports.
Data frame output
Use output = "data.frame" for the table as it is
displayed, with its numbers: one row per printed row, the key columns
variable (the column name), label,
level and .row_role
("factor_header" for the row of a variable, which carries
its p-value and association measure, "level", or
"missing" for the row of missing values), then the counts,
the full-precision percentages, p and the measure under the
names the table prints. as.data.frame() on the printed
table returns the same frame:
table_categorical(
sochealth,
select = smoking,
by = education,
output = "data.frame"
)
#> variable label level .row_role Lower secondary n Lower secondary %
#> 1 smoking smoking <NA> factor_header NA NA
#> 2 smoking smoking No level 179 69.64981
#> 3 smoking smoking Yes level 78 30.35019
#> 4 smoking smoking (Missing) missing 4 NA
#> Upper secondary n Upper secondary % Tertiary n Tertiary % Total n Total %
#> 1 NA NA NA NA NA NA
#> 2 415 78.74763 332 84.91049 926 78.80851
#> 3 112 21.25237 59 15.08951 249 21.19149
#> 4 12 NA 9 NA 25 NA
#> p V
#> 1 2.012877e-05 0.1356677
#> 2 NA NA
#> 3 NA NA
#> 4 NA NAUse output = "long" for one row per level and group, the
Total margin included and flagged by total,
with the test of each variable (test_type,
statistic, df, p.value) and its
association measure (es_type, es_value) on
every row of its block:
head(table_categorical(
sochealth,
select = smoking,
by = education,
output = "long"
), 4)
#> variable label level .row_role group .group_role total n
#> 1 smoking smoking No level Lower secondary group FALSE 179
#> 2 smoking smoking No level Upper secondary group FALSE 415
#> 3 smoking smoking No level Tertiary group FALSE 332
#> 4 smoking smoking No level Total total TRUE 926
#> pct test_type statistic df p.value es_type es_value es_ci_lower
#> 1 69.64981 chi_squared 21.62672 2 2.012877e-05 cramer_v 0.1356677 NA
#> 2 78.74763 chi_squared 21.62672 2 2.012877e-05 cramer_v 0.1356677 NA
#> 3 84.91049 chi_squared 21.62672 2 2.012877e-05 cramer_v 0.1356677 NA
#> 4 78.80851 chi_squared 21.62672 2 2.012877e-05 cramer_v 0.1356677 NA
#> es_ci_upper smd_type smd_value
#> 1 NA <NA> NA
#> 2 NA <NA> NA
#> 3 NA <NA> NA
#> 4 NA <NA> NACustom labels
By default, table_categorical() labels each row block
with the column name. labels = TRUE uses the variable’s
label attribute when one is present (e.g. data imported with
haven), and the column name otherwise. A named
character vector keyed by column name sets the labels you
publish: the listed columns take them, and the others follow
options(spicy.var_labels) (their name unless it is
TRUE).
labels = var_labels(smoking = "Smoking status") renames the
same way while the others keep their label attribute. A name that
matches no column of the table warns and is left out, so one vector can
still serve every table of a report (wrap the call in
suppressWarnings() to quiet it). The by
variable in the title follows the same rule, as in the other summary
tables. (Unnamed positional label vectors, accepted before 0.13.0, now
raise an error.)
table_categorical(
sochealth,
select = c(smoking, physical_activity),
by = education,
labels = c(
smoking = "Smoking status",
physical_activity = "Regular physical activity"
)
)
#> Categorical table by education
#>
#> Lower secondary Upper secondary Tertiary
#> ─────────────── ─────────────── ─────────
#> Variable │ n % n % n %
#> ───────────────────────────┼─────────────────────────────────────────────
#> Smoking status │
#> No │ 179 69.6 415 78.7 332 84.9
#> Yes │ 78 30.4 112 21.3 59 15.1
#> (Missing) │ 4 12 9
#> ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌
#> Regular physical activity │
#> No │ 177 67.8 310 57.5 163 40.8
#> Yes │ 84 32.2 229 42.5 237 59.2
#>
#> Total
#> ─────────
#> Variable │ n % p V
#> ───────────────────────────┼───────────────────────
#> Smoking status │ <.001 .14
#> No │ 926 78.8
#> Yes │ 249 21.2
#> (Missing) │ 25
#> ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌
#> Regular physical activity │ <.001 .21
#> No │ 650 54.2
#> Yes │ 550 45.8
#>
#> Note. N = 1200: Lower secondary (n = 261), Upper secondary (n = 539), Tertiary (n = 400). Percentages are column percentages. P-values: Pearson chi-squared test. V = Cramér's V.Association measures and confidence intervals
table_categorical() picks the association measure per
row variable based on the variable type
(assoc_measure = "auto", the default):
-
2x2 (binary row variable vs. binary
by) ->phi, - both ordered factors -> Kendall’s
tau_b, - otherwise -> Cramér’s
V.
A measure used for every row heads the column, and names it in the
data frames, with its symbol (V for Cramér’s V, φ for phi, τb for
Kendall’s tau-b, γ for gamma; the other measures keep their names). The
note defines the symbol as it defines any abbreviation: V by default,
the Greek letters under spicy_style(abbreviations = "all").
When the chosen measures differ across rows, the column header collapses
to "Effect size" and the table note names the measure used
for each variable.
Seven measures are available: "cramer_v",
"phi", "gamma", "tau_b",
"tau_c", "somers_d", and
"lambda"; assoc_measure = "none" drops the
column entirely. See ?table_categorical for the dispatch
details and Cramér’s V, Phi, and
association measures for definitions and guidance on choosing
among them. Override the automatic choice with a single string for
uniform application, or with a named vector to mix measures per row:
# Uniform: same measure for every row variable
table_categorical(
sochealth,
select = smoking,
by = education,
assoc_measure = "lambda"
)
#> Categorical table by education
#>
#> Lower secondary Upper secondary Tertiary Total
#> ─────────────── ─────────────── ───────── ─────────
#> Variable │ n % n % n % n % p
#> ─────────────┼───────────────────────────────────────────────────────────────
#> smoking │ <.001
#> No │ 179 69.6 415 78.7 332 84.9 926 78.8
#> Yes │ 78 30.4 112 21.3 59 15.1 249 21.2
#> (Missing) │ 4 12 9 25
#>
#> Variable │ Lambda
#> ─────────────┼────────
#> smoking │ .00
#> No │
#> Yes │
#> (Missing) │
#>
#> Note. N = 1200: Lower secondary (n = 261), Upper secondary (n = 539), Tertiary (n = 400). Percentages are column percentages. P-value: Pearson chi-squared test.A significant chi-squared p-value next to a lambda of exactly .00 is not a contradiction. Goodman-Kruskal lambda measures the proportional reduction in the error of predicting the row variable once the group is known, and it is exactly 0 whenever the modal category is the same in every group: here “No” is the most frequent answer at all three education levels (69.6%, 78.7%, 84.9%), so knowing education never changes the best single guess, even though the distributions clearly differ (hence the significant chi-squared test).
In a named vector, variables you do not name keep the
"auto" choice, so only the overrides need to be listed.
Here "auto" would pick Cramér’s V for smoking
(binary x ordered, not 2x2) and Kendall’s Tau-b for
self_rated_health (ordered x ordered); the named vector
keeps the former and replaces the latter with Goodman-Kruskal Gamma:
# Named vector: override "auto" for one variable only
table_categorical(
sochealth,
select = c(smoking, self_rated_health),
by = education,
assoc_measure = c(self_rated_health = "gamma")
)
#> Categorical table by education
#>
#> Lower secondary Upper secondary Tertiary Total
#> ─────────────── ─────────────── ───────── ─────────
#> Variable │ n % n % n % n %
#> ───────────────────┼────────────────────────────────────────────────────────
#> smoking │
#> No │ 179 69.6 415 78.7 332 84.9 926 78.8
#> Yes │ 78 30.4 112 21.3 59 15.1 249 21.2
#> (Missing) │ 4 12 9 25
#> ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌
#> self_rated_health │
#> Poor │ 28 10.8 28 5.3 5 1.3 61 5.2
#> Fair │ 86 33.1 118 22.4 62 15.8 266 22.5
#> Good │ 102 39.2 263 49.9 193 49.1 558 47.3
#> Very good │ 44 16.9 118 22.4 133 33.8 295 25.0
#> (Missing) │ 1 12 7 20
#>
#> Variable │ p Effect size
#> ───────────────────┼────────────────────
#> smoking │ <.001 .14
#> No │
#> Yes │
#> (Missing) │
#> ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌
#> self_rated_health │ <.001 .31
#> Poor │
#> Fair │
#> Good │
#> Very good │
#> (Missing) │
#>
#> Note. N = 1200: Lower secondary (n = 261), Upper secondary (n = 539), Tertiary (n = 400). Percentages are column percentages. P-values: Pearson chi-squared test. Cramér's V: smoking. Goodman-Kruskal Gamma: self_rated_health.smoking keeps its automatic Cramér’s V (.14) while
self_rated_health switches from the automatic Tau-b (.20)
to Gamma (.31) – Gamma is larger on the same table because it ignores
tied pairs. Since the two measures differ, the header collapses to
"Effect size" and the note documents the per-row
choice.
Add confidence intervals with assoc_ci = TRUE. In the
rendered formats (gt, tinytable,
flextable, word) the CI is shown inline after
the measure, e.g. .14 [.08, .19], under a header that
states its level, V [95% CI] (demonstrated in the final
section). In the default console table and in the
"data.frame", "excel" and
"clipboard" outputs, separate columns named
95% CI LL and 95% CI UL are added, the names
the other tables give their interval columns in a data frame; in the
long format ("long") the bounds fill
es_ci_lower / es_ci_upper:
table_categorical(
sochealth,
select = smoking,
by = education,
assoc_ci = TRUE,
output = "data.frame"
)
#> variable label level .row_role Lower secondary n Lower secondary %
#> 1 smoking smoking <NA> factor_header NA NA
#> 2 smoking smoking No level 179 69.64981
#> 3 smoking smoking Yes level 78 30.35019
#> 4 smoking smoking (Missing) missing 4 NA
#> Upper secondary n Upper secondary % Tertiary n Tertiary % Total n Total %
#> 1 NA NA NA NA NA NA
#> 2 415 78.74763 332 84.91049 926 78.80851
#> 3 112 21.25237 59 15.08951 249 21.19149
#> 4 12 NA 9 NA 25 NA
#> p V 95% CI LL 95% CI UL
#> 1 2.012877e-05 0.1356677 0.07909264 0.1913716
#> 2 NA NA NA NA
#> 3 NA NA NA NA
#> 4 NA NA NA NAChi-squared or Fisher’s exact test
The chi-squared test is an approximation, unreliable when expected
counts are small. With test = "auto", the default, each
variable takes Pearson’s chi-squared test when every expected count of
its table is at least 5, and Fisher’s exact test otherwise: the rule of
gtsummary’s add_p(). The note names the test of each
variable. In the first 40 respondents, smoking has an
expected count of 3.6 and takes the exact test:
table_categorical(
sochealth[1:40, ],
select = c(smoking, physical_activity),
by = sex
)
#> Categorical table by sex
#>
#> Female Male Total
#> ──────────── ──────────── ────────────
#> Variable │ n % n % n % p φ
#> ─────────────────────┼─────────────────────────────────────────────────────────
#> smoking │ .258 .20
#> No │ 16 72.7 16 88.9 32 80.0
#> Yes │ 6 27.3 2 11.1 8 20.0
#> ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌
#> physical_activity │ .726 .06
#> No │ 11 50.0 8 44.4 19 47.5
#> Yes │ 11 50.0 10 55.6 21 52.5
#>
#> Note. N = 40: Female (n = 22), Male (n = 18). Percentages are column percentages. P-values: Pearson chi-squared test (physical_activity); Fisher exact test (smoking).test = "chisq" tests every variable by the chi-squared,
as before 0.14.0, and test = "fisher" tests every variable
exactly. Fisher’s exact test of a table larger than 2x2 is the
Freeman-Halton extension. When its exact enumeration fails on a large
sparse table, the p-value is its Monte Carlo estimate over
simulate_B tables, and the note says so; set a seed to
reproduce it. The long output gives the test of each variable in
test_type.
A 2x2 table, a two-level variable by two groups, has two more tests.
test = "midp" takes the Fisher mid-p test, which counts the
tables as probable as the observed one at half their probability: it is
less conservative than Fisher’s exact test, and Fagerland, Lydersen and
Laake (2017) recommend it at every sample size. test = "n1"
takes Campbell’s N-1 chi-squared test when every expected count is at
least 1, and Fisher’s exact test otherwise. A larger table keeps the
"auto" rule, and the note names the test of each
variable:
table_categorical(
sochealth[1:40, ],
select = c(smoking, education),
by = sex,
test = "midp"
)
#> Categorical table by sex
#>
#> Female Male Total
#> ──────── ──────── ────────
#> Variable │ n % n % n % p Effect size
#> ───────────────────┼─────────────────────────────────────────────────
#> smoking │ .184 .20
#> No │ 16 72.7 16 88.9 32 80.0
#> Yes │ 6 27.3 2 11.1 8 20.0
#> ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌
#> education │ .461 .21
#> Lower secondary │ 6 27.3 2 11.1 8 20.0
#> Upper secondary │ 10 45.5 9 50.0 19 47.5
#> Tertiary │ 6 27.3 7 38.9 13 32.5
#>
#> Note. N = 40: Female (n = 22), Male (n = 18). Percentages are column percentages. P-values: Fisher exact test (education); Fisher mid-p test (smoking). Phi: smoking. Cramér's V: education.Descriptive tables without tests
The test and the association measure are two separate choices:
p_value = FALSE removes the test (the p
column, and test_type, statistic,
df and p.value from the long output), and
assoc_measure = "none" removes the measure. Together they
give a purely descriptive table, with the same group columns and
headers:
table_categorical(
sochealth,
select = c(smoking, physical_activity),
by = sex,
p_value = FALSE,
assoc_measure = "none"
)
#> Categorical table by sex
#>
#> Female Male Total
#> ───────────── ───────────── ─────────────
#> Variable │ n % n % n %
#> ─────────────────────┼─────────────────────────────────────────────
#> smoking │
#> No │ 475 78.4 451 79.3 926 78.8
#> Yes │ 131 21.6 118 20.7 249 21.2
#> (Missing) │ 14 11 25
#> ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌
#> physical_activity │
#> No │ 334 53.9 316 54.5 650 54.2
#> Yes │ 286 46.1 264 45.5 550 45.8
#>
#> Note. N = 1200: Female (n = 620), Male (n = 580). Percentages are column percentages.Balance: the standardized mean difference
For a baseline table read as a balance check rather than a
significance test, smd = TRUE adds the standardized mean
difference between the two groups of by, on the variable
row beside p:
table_categorical(
sochealth,
select = c(smoking, self_rated_health),
by = sex,
smd = TRUE
)
#> Categorical table by sex
#>
#> Female Male Total
#> ───────── ───────── ─────────
#> Variable │ n % n % n % p Effect size SMD
#> ───────────────────┼──────────────────────────────────────────────────────────
#> smoking │ .713 .01 0.02
#> No │ 475 78.4 451 79.3 926 78.8
#> Yes │ 131 21.6 118 20.7 249 21.2
#> (Missing) │ 14 11 25
#> ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌
#> self_rated_health │ .849 .03 0.05
#> Poor │ 31 5.1 30 5.3 61 5.2
#> Fair │ 143 23.4 123 21.6 266 22.5
#> Good │ 282 46.2 276 48.4 558 47.3
#> Very good │ 154 25.2 141 24.7 295 25.0
#> (Missing) │ 10 10 20
#>
#> Note. N = 1200: Female (n = 620), Male (n = 580). Percentages are column percentages. P-values: Pearson chi-squared test. Phi: smoking. Cramér's V: self_rated_health. SMD direction: Female − Male. The usual imbalance threshold is |SMD| > 0.1. For a variable with more than two categories the SMD is the multivariate (Mahalanobis) distance between the two profiles of proportions, and is therefore unsigned. SMD = standardized mean difference.Two categories give the Bernoulli form, signed,
group 1 minus group 2 in the order the table displays them. Three or
more give the multivariate (Mahalanobis) distance between the two
profiles of proportions: a distance, so it has no sign and no upper
bound of 1 — the table note says so whenever such a variable is present,
and the "long" output names the kernel each row took in
smd_type.
Exactly two groups are required, as in
table_continuous(). The "(Missing)" level of
drop_na = FALSE is displayed and never enters the
diagnostic. There is no confidence interval and no p-value on
this column by design. Under weights the profiles are the
weighted proportions, and because a profile of proportions is unchanged
by a global rescaling of the weights, rescale cannot move
this column.
A balance table usually shows no test: p_value = FALSE
removes the categorical p column as
table_continuous(p_value = FALSE) removes its own, so a
mixed balance table can drop both. When the p column stays, it
can be adjusted: p_adjust = "holm" (or "BH")
adjusts the tests of all the variables together, and the note says
so.
Weighted tables
Pass survey weights with the weights argument. By
default (rescale = FALSE) the weights are used as-is;
rescale = TRUE rescales them so the total weighted N equals
the number of observations (here 1200, against a raw weight sum of
1196.474). Displayed counts are weighted counts rounded to integers at
display time – the SPSS Crosstabs convention – while the machine formats
("data.frame", "long") carry the exact
fractional weighted counts:
table_categorical(
sochealth,
select = c(smoking, physical_activity),
by = education,
weights = "weight",
rescale = TRUE
)
#> Categorical table by education
#>
#> Lower secondary Upper secondary Tertiary Total
#> ─────────────── ─────────────── ───────── ─────────
#> Variable │ n % n % n % n %
#> ───────────────────┼────────────────────────────────────────────────────────
#> smoking │
#> No │ 176 69.0 419 78.5 325 84.4 919 78.4
#> Yes │ 79 31.0 114 21.5 60 15.6 254 21.6
#> (Missing) │ 4 13 10 27
#> ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌
#> physical_activity │
#> No │ 174 67.2 315 57.7 166 41.9 655 54.6
#> Yes │ 85 32.8 231 42.3 229 58.1 545 45.4
#>
#> Variable │ p V
#> ───────────────────┼────────────
#> smoking │ <.001 .13
#> No │
#> Yes │
#> (Missing) │
#> ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌
#> physical_activity │ <.001 .19
#> No │
#> Yes │
#>
#> Note. N = 1200 (unweighted): Lower secondary (n = 261), Upper secondary (n = 539), Tertiary (n = 400). Percentages are column percentages. Statistics weighted by weight. P-values: Pearson chi-squared test. V = Cramér's V.Handling missing values
By default, missing values are displayed as a “(Missing)” category
(drop_na = FALSE), with their count and no percentage: the
percentages are computed on the observed values.
percent_base = "total" puts the missing values back in the
base, the percentages then summing over every observation, as before
0.14.0. Set drop_na = TRUE to remove them. The removal
happens before each cross-tabulation, variable by variable: each row
variable keeps its own complete cases (on itself and on
by), so the count of a variable can differ from the N of
the note and across variables within the same table – this is
available-case analysis per cross-table, not listwise deletion over the
whole selection. The removal is disclosed in a table note rather than
silent:
table_categorical(
sochealth,
select = income_group,
by = education,
drop_na = TRUE
)
#> Categorical table by education
#>
#> Lower secondary Upper secondary Tertiary Total
#> ─────────────── ─────────────── ───────── ─────────
#> Variable │ n % n % n % n % p
#> ────────────────┼───────────────────────────────────────────────────────────────
#> income_group │ <.001
#> Low │ 87 33.7 115 21.7 45 11.4 247 20.9
#> Lower middle │ 92 35.7 186 35.1 110 27.9 388 32.8
#> Upper middle │ 58 22.5 135 25.5 135 34.3 328 27.7
#> High │ 21 8.1 94 17.7 104 26.4 219 18.5
#>
#> Variable │ τb
#> ────────────────┼─────
#> income_group │ .22
#> Low │
#> Lower middle │
#> Upper middle │
#> High │
#>
#> Note. N = 1200: Lower secondary (n = 261), Upper secondary (n = 539), Tertiary (n = 400). Percentages are column percentages. Missing values removed: income_group (18). P-value: Pearson chi-squared test.With several selected variables the note lists each variable’s
removals separately: selecting smoking and
physical_activity together under
drop_na = TRUE keeps 1175 and 1200 complete cases
respectively, in the same table.
A level of your data that already reads “(Missing)” would sit beside
that category under the same label, and a level of by named
“Total” beside the margin. The table then stops with an error that gives
the two ways out: rename the level, or give the category another label
with
options(spicy.labels = list(row_missing_level = "(Not stated)"))
(the margin’s key is header_margin_total). A level of
by that is the empty string, which read.csv()
makes of an empty text field, is an error too: a group is named in the
header and in the note. Recode it to NA, or to a label.
Filtering and reordering levels
Use levels_keep to display only specific levels. The
order you specify controls the display order, which is useful for
placing “(Missing)” first to highlight missingness:
table_categorical(
sochealth,
select = income_group,
by = education,
drop_na = FALSE,
levels_keep = c("(Missing)", "Low", "High")
)
#> Categorical table by education
#>
#> Lower secondary Upper secondary Tertiary Total
#> ─────────────── ─────────────── ───────── ─────────
#> Variable │ n % n % n % n % p
#> ──────────────┼───────────────────────────────────────────────────────────────
#> income_group │ <.001
#> (Missing) │ 3 9 6 18
#> Low │ 87 33.7 115 21.7 45 11.4 247 20.9
#> High │ 21 8.1 94 17.7 104 26.4 219 18.5
#>
#> Variable │ τb
#> ──────────────┼─────
#> income_group │ .22
#> (Missing) │
#> Low │
#> High │
#>
#> Note. N = 1200: Lower secondary (n = 261), Upper secondary (n = 539), Tertiary (n = 400). Percentages are column percentages. P-value: Pearson chi-squared test.levels_keep filters the display only: counts,
percentages, the chi-squared test, and the association measure are all
still computed on the full cross-table. That is why the displayed
percentages no longer sum to 100 (within “Lower secondary”: 33.7 + 8.1 =
41.8 – the hidden “Lower middle” and “Upper middle” levels still count
in the denominator), and why p and Tau-b are identical to the
unfiltered table. To recompute the statistics on a subset of levels,
filter the data before calling table_categorical().
Formatting options
Control the number of digits for percentages, p-values, and the association measure:
table_categorical(
sochealth,
select = smoking,
by = education,
percent_digits = 2,
p_digits = 4,
effect_size_digits = 3
)
#> Categorical table by education
#>
#> Lower secondary Upper secondary Tertiary Total
#> ─────────────── ─────────────── ────────── ──────────
#> Variable │ n % n % n % n % p
#> ─────────────┼──────────────────────────────────────────────────────────────────
#> smoking │ <.0001
#> No │ 179 69.65 415 78.75 332 84.91 926 78.81
#> Yes │ 78 30.35 112 21.25 59 15.09 249 21.19
#> (Missing) │ 4 12 9 25
#>
#> Variable │ V
#> ─────────────┼──────
#> smoking │ .136
#> No │
#> Yes │
#> (Missing) │
#>
#> Note. N = 1200: Lower secondary (n = 261), Upper secondary (n = 539), Tertiary (n = 400). Percentages are column percentages. P-value: Pearson chi-squared test. V = Cramér's V.p_digits drives both the displayed precision of the
p column and the small-p threshold
(p_digits = 3 -> <.001,
p_digits = 4 -> <.0001), matching
table_continuous() and
table_continuous_lm().
Decimal alignment
By default (align = "decimal") numeric columns are
aligned on the decimal mark, the standard scientific-publication
convention (SPSS, SAS, LaTeX siunitx). Numeric cells are
pre-padded with figure-spaces (U+2007, spaces exactly one digit wide) so
that every string in a column has the same width with the decimal mark
at the same internal position; centering those uniform-width strings
then stacks the decimal points vertically. The same pad-then-center
strategy is applied on every rendering engine (gt,
tinytable, flextable, word, ASCII
print) for a homogeneous rendering – same single-font policy as
table_regression(). The clipboard is the exception: its
payload is delimited text meant to be parsed, and a padded number would
paste as text next to an unpadded number, so its cells travel unpadded.
The native gt::cols_align_decimal() and
tinytable::style_tt(align = "d") primitives are
deliberately not used: the former renders visually right-aligned and the
latter centers each cell on its own value rather than on the decimal
mark, which would be inconsistent with the other engines.
"center" and "right" apply literal
alignment:
table_categorical(
sochealth,
select = c(smoking, physical_activity),
by = sex,
align = "right"
)
#> Categorical table by sex
#>
#> Female Male Total
#> ───────── ───────── ─────────
#> Variable │ n % n % n % p φ
#> ───────────────────┼────────────────────────────────────────────
#> smoking │ .713 .01
#> No │ 475 78.4 451 79.3 926 78.8
#> Yes │ 131 21.6 118 20.7 249 21.2
#> (Missing) │ 14 11 25
#> ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌
#> physical_activity │ .832 .01
#> No │ 334 53.9 316 54.5 650 54.2
#> Yes │ 286 46.1 264 45.5 550 45.8
#>
#> Note. N = 1200: Female (n = 620), Male (n = 580). Percentages are column percentages. P-values: Pearson chi-squared test.Tidying for downstream pipelines
table_categorical() returns an object that can be
coerced to a plain data.frame / tbl_df (the
displayed table, as with output = "data.frame") or piped
into broom::tidy() / broom::glance() for any
downstream tidyverse-stats workflow:
out <- table_categorical(
sochealth,
select = c(smoking, physical_activity),
by = sex
)
# One row per (variable x level x group) with broom-style columns
# (variable, label, level, .row_role, group, .group_role, total, n,
# proportion): the column name and the label displayed. The Total
# margin is flagged by `total`; filter it out with `!total` to count
# each observation once.
broom::tidy(out)
#> # A tibble: 15 × 9
#> variable label level .row_role group .group_role total n proportion
#> <chr> <chr> <chr> <chr> <chr> <chr> <lgl> <int> <dbl>
#> 1 smoking smok… No level Fema… group FALSE 475 0.784
#> 2 smoking smok… No level Male group FALSE 451 0.793
#> 3 smoking smok… No level Total total TRUE 926 0.788
#> 4 smoking smok… Yes level Fema… group FALSE 131 0.216
#> 5 smoking smok… Yes level Male group FALSE 118 0.207
#> 6 smoking smok… Yes level Total total TRUE 249 0.212
#> 7 smoking smok… (Mis… missing Fema… group FALSE 14 NA
#> 8 smoking smok… (Mis… missing Male group FALSE 11 NA
#> 9 smoking smok… (Mis… missing Total total TRUE 25 NA
#> 10 physical_acti… phys… No level Fema… group FALSE 334 0.539
#> 11 physical_acti… phys… No level Male group FALSE 316 0.545
#> 12 physical_acti… phys… No level Total total TRUE 650 0.542
#> 13 physical_acti… phys… Yes level Fema… group FALSE 286 0.461
#> 14 physical_acti… phys… Yes level Male group FALSE 264 0.455
#> 15 physical_acti… phys… Yes level Total total TRUE 550 0.458
# One row per variable, in the order of `select`, with its test
# (chi-squared or Fisher) and the chosen association measure
# (test_type, statistic, df, p.value, es_type, es_value,
# es_ci_lower / es_ci_upper, smd_type, smd_value), and its counts.
broom::glance(out)
#> # A tibble: 2 × 16
#> variable label test_type statistic df p.value es_type es_value es_ci_lower
#> <chr> <chr> <chr> <dbl> <int> <dbl> <chr> <dbl> <dbl>
#> 1 smoking smok… chi_squa… 0.136 1 0.713 phi 0.0107 NA
#> 2 physical… phys… chi_squa… 0.0452 1 0.832 phi 0.00614 NA
#> # ℹ 7 more variables: es_ci_upper <dbl>, smd_type <chr>, smd_value <dbl>,
#> # nobs <int>, nobs_valid <int>, weighted_nobs <dbl>,
#> # weighted_nobs_valid <dbl>
# The counts are the bases of the percentages: nobs counts the 25
# missing answers of smoking, its (Missing) row, and nobs_valid leaves
# them out.
broom::glance(out)[c("variable", "nobs", "nobs_valid")]
#> # A tibble: 2 × 3
#> variable nobs nobs_valid
#> <chr> <int> <int>
#> 1 smoking 1200 1175
#> 2 physical_activity 1200 1200Multiple-response items
A “check all that apply” question is a set of yes/no items answered
by the same respondents, like the five info_* items of
sochealth, the sources of health information used in the
past 12 months. It is not one categorical variable: the choices
outnumber the respondents, and the chi-squared test of the
items-by-groups table is not valid. table_multiresponse()
reads the items as one question, with its own bases, percentages, and
tests, as Multiple-response
questions explains.
A battery of items rated on one scale, such as a Likert grid, reads
better with one row per item and one column per level than with one
block of rows per item: table_battery() gives that layout,
as Item batteries shows.
Rendered outputs and export
The rendered formats produce publication-ready tables for HTML and
Word workflows. The "gt" format produces a table with
APA-style borders, column spanners, and decimal alignment:
pkgdown_dark_gt(
table_categorical(
sochealth,
select = c(smoking, physical_activity, dentist_12m),
by = education,
output = "gt"
)
)| Categorical table by education | ||||||||||
|
Variable
|
Lower secondary
|
Upper secondary
|
Tertiary
|
Total
|
p
|
V
|
||||
|---|---|---|---|---|---|---|---|---|---|---|
| n | % | n | % | n | % | n | % | |||
| smoking | <.001 | .14 | ||||||||
| No | 179 | 69.6 | 415 | 78.7 | 332 | 84.9 | 926 | 78.8 | ||
| Yes | 78 | 30.4 | 112 | 21.3 | 59 | 15.1 | 249 | 21.2 | ||
| (Missing) | 4 | 12 | 9 | 25 | ||||||
| physical_activity | <.001 | .21 | ||||||||
| No | 177 | 67.8 | 310 | 57.5 | 163 | 40.8 | 650 | 54.2 | ||
| Yes | 84 | 32.2 | 229 | 42.5 | 237 | 59.2 | 550 | 45.8 | ||
| dentist_12m | <.001 | .22 | ||||||||
| No | 113 | 43.3 | 174 | 32.3 | 67 | 16.8 | 354 | 29.5 | ||
| Yes | 148 | 56.7 | 365 | 67.7 | 333 | 83.2 | 846 | 70.5 | ||
The "tinytable" format applies the same layout
conventions through the lightweight tinytable engine (here a two-group
table by sex):
table_categorical(
sochealth,
select = c(smoking, physical_activity),
by = sex,
output = "tinytable"
)| Variable | Female | Male | Total | p | φ | |||
|---|---|---|---|---|---|---|---|---|
| n | % | n | % | n | % | |||
Note. N = 1200: Female (n = 620), Male (n = 580). Percentages are column percentages. P-values: Pearson chi-squared test. | ||||||||
| smoking | .713 | .01 | ||||||
| No | 475 | 78.4 | 451 | 79.3 | 926 | 78.8 | ||
| Yes | 131 | 21.6 | 118 | 20.7 | 249 | 21.2 | ||
| (Missing) | 14 | 11 | 25 | |||||
| physical_activity | .832 | .01 | ||||||
| No | 334 | 53.9 | 316 | 54.5 | 650 | 54.2 | ||
| Yes | 286 | 46.1 | 264 | 45.5 | 550 | 45.8 | ||
With assoc_ci = TRUE, the rendered formats show the
confidence interval inline after the association measure:
pkgdown_dark_gt(
table_categorical(
sochealth,
select = c(smoking, physical_activity),
by = education,
assoc_ci = TRUE,
output = "gt"
)
)| Categorical table by education | ||||||||||
|
Variable
|
Lower secondary
|
Upper secondary
|
Tertiary
|
Total
|
p
|
V [95% CI]
|
||||
|---|---|---|---|---|---|---|---|---|---|---|
| n | % | n | % | n | % | n | % | |||
| smoking | <.001 | .14 [.08, .19] | ||||||||
| No | 179 | 69.6 | 415 | 78.7 | 332 | 84.9 | 926 | 78.8 | ||
| Yes | 78 | 30.4 | 112 | 21.3 | 59 | 15.1 | 249 | 21.2 | ||
| (Missing) | 4 | 12 | 9 | 25 | ||||||
| physical_activity | <.001 | .21 [.15, .26] | ||||||||
| No | 177 | 67.8 | 310 | 57.5 | 163 | 40.8 | 650 | 54.2 | ||
| Yes | 84 | 32.2 | 229 | 42.5 | 237 | 59.2 | 550 | 45.8 | ||
For Excel export, provide a file path:
table_categorical(
sochealth,
select = c(smoking, physical_activity, dentist_12m),
by = education,
output = "excel",
excel_path = "my_table.xlsx"
)For Word, use output = "word":
table_categorical(
sochealth,
select = c(smoking, physical_activity, dentist_12m),
by = education,
output = "word",
word_path = "my_table.docx"
)You can also copy directly to the clipboard for pasting into a spreadsheet or a text editor:
table_categorical(
sochealth,
select = c(smoking, physical_activity),
by = education,
output = "clipboard"
)See also
- See Continuous summary tables for the continuous counterpart with classical group-comparison tests.
- See Model-based continuous summary tables for model-based continuous summary tables.
- See Publication-ready regression
tables for the full coefficient table from one or several
fitted
lm/glmmodels (APA Table 3). - See Summary tables for reporting for a cross-function reporting workflow that ties the summary-table functions together along the APA Table 1 / 2 / 3 sequence.