Categorical summary table from a survey design
Source:R/table_categorical_svy.R
table_categorical_svy.RdThe design twin of table_categorical(): counts and estimated
percentages of categorical variables computed from a
survey::svydesign() or survey::as.svrepdesign() object instead
of a data frame.
Every statistic is survey's. survey::svymean() estimates the
percentages and their design effects, survey::svyciprop() their
confidence intervals, and survey::svychisq() tests the
association, Rao-Scott corrected and referred to the design degrees
of freedom.
Usage
table_categorical_svy(
design,
select = tidyselect::everything(),
by = NULL,
labels = getOption("spicy.var_labels", FALSE),
note_labels = NULL,
levels_keep = NULL,
factor_levels = c("observed", "all"),
include_total = TRUE,
drop_na = FALSE,
proportion_ci = FALSE,
ci_method = c("logit", "likelihood", "asin", "beta", "mean", "xlogit", "wilson"),
ci_level = 0.95,
chisq_statistic = c("F", "Chisq", "Wald", "adjWald", "saddlepoint"),
deff = FALSE,
df = NULL,
p_value = NULL,
p_adjust = "none",
percent_base = c("valid", "total"),
percent_digits = 1,
p_digits = 3,
decimal_mark = ".",
align = c("decimal", "center", "right"),
note = NULL,
note_add = NULL,
output = c("default", "data.frame", "long", "tinytable", "gt", "flextable", "excel",
"clipboard", "word"),
indent_text = " ",
indent_text_excel_clipboard = strrep(" ", 6),
excel_path = NULL,
excel_sheet = NULL,
clipboard_delim = "\t",
word_path = NULL,
word_template = NULL,
user_na = TRUE,
style = NULL
)Arguments
- design
A survey design:
survey::svydesign()orsurvey::as.svrepdesign().- select
Columns to tabulate, as a tidyselect expression on the design's variables. When omitted, every categorical column of the design (factor, character, logical, and labelled columns), as in
table_categorical(); an explicitselectis taken verbatim, so a numeric-coded variable can still be tabulated by naming it. The design's own columns are not variables to describe: its sampling weights, replicate weights, cluster identifiers (every stage, unless each cluster of a one-stage design is a single observation) and finite population corrections.everything()and the other selection helpers skip them, and naming one, or giving its position, is an error;table_categorical()describes it from the data. Strata stay variables, since a stratification variable such as a region is often one of interest. These columns are read from the design object. A design made bysurvey::as.svrepdesign()records none of them, and one made bysurvey::svrepdesign()names its sampling weights only in its call, as a formula, untilsubset(),update(),postStratify(),calibrate(),rake()ortrimWeights()replaces the call: leave such a column out with a negation (select = !w).- by
A single grouping column: one column block per level, in the order of
table_categorical()(a factor's levels, any other column sorted: text in the C locale,FALSEbeforeTRUE, numbers ascending), the order the levels of each variable follow too.- labels
How each variable is named in the table: in the rows, in the title, and in the notes. Four forms:
labels = FALSEshows the column name.labels = TRUEshows the column'slabelattribute (as set byhaven,labelled, orlabel_from_names()) when it is present, notNA, and not empty, and the column name otherwise.labels = c(bmi = "Body mass index"), a named character vector, gives the columns it names these labels. Every other column followsoptions(spicy.var_labels): its name when the option is unset orFALSE, itslabelattribute when it isTRUE.labels = var_labels(bmi = "BMI (kg/m2)")gives the columns it names these labels, and every other column itslabelattribute, whatever the option says.var_labels()alone islabels = TRUE.
A name that matches no column of the table warns (class
spicy_unknown_name) and is left out, so one vector can still serve every table of a project. The default readsoptions(spicy.var_labels), and aTRUEorFALSEtyped in the call wins over it. Any other value,NULLincluded, is an error. A variable label documents the data file; a published table carries the wording you set here.note_labelsgives a variable a shorter label in the title and the notes.- note_labels
The label a variable takes where the table names it in a sentence, in the title and in the notes, in place of the one
labelsgives it: a named character vector,note_labels = c(sex = "sex at birth"), or avar_labels()object, which reads as one.labelscan then name a row with a whole question while the note says "Missing values removed: sex at birth (2).". The rows, the column headers and the spanners keep the labels oflabels, and so do the title and the notes for a variablenote_labelsdoes not name. A name that matches no column warns and is left out, as inlabels, andNULL(the default) renames nothing. A note label that another variable of the table shows is an error (classspicy_label_collision): choose another one, or relabel the other variable.- levels_keep
Levels to keep, as a character vector (all variables) or a named list (per variable). A declared level with no observation that it names is shown with a count of 0, whatever
factor_levelssays.- factor_levels
Character. Controls how factor and labelled values are displayed in the table, as in
freq()."observed"(the default; matches Stata'staband SPSSFREQUENCIES, which both list only values present in the data) shows only levels present in the data."all"keeps every declared level, including unused ones, which appear withn = 0and a percentage of 0 (in every column underby). A character or logical column declares no level. The rows of unused levels are displayed only: they change no percentage of the other rows and no test, which runs on the observed levels. Underproportion_ci = TRUE, an unused level gets the exact interval of a percentage of 0, the one a group that does not observe a level gets.- include_total
Add a
Totalcolumn block with the whole design's percentages (defaultTRUE, only withby). A group displayed with the label of that block is an error, as intable_categorical().- drop_na
Drop missing values. A table that counts shows them by default, the rule of
table_categorical():FALSE(the default) shows them as a(Missing)level, and a level displayed with that label beside them is an error, as there. Under the defaultpercent_base = "valid", that row shows their count and no percentage. Shown or dropped, they never enter the test: the p-value is computed on the complete cases either way, which is the conventiontable_categorical()applies. Dropped, they are counted in the note,bylast: a missingbytakes the observation out of every variable of the table, a missing value only out of its own variable. Underdrop_na = TRUE, abythat no observation holds is an error (classspicy_invalid_data).- proportion_ci
Add the confidence interval of each percentage.
- ci_method
Interval method passed to
survey::svyciprop():"logit"(default),"likelihood","asin","beta","mean","xlogit"or"wilson"."logit"and"likelihood"fit a logistic regression, which does not allow negative weights: where the weights of a domain change sign, as linear calibration can make them, its intervals are not reported, the note says so and the call warns (spicy_negative_weights_no_ci). The five other methods accept negative weights.- ci_level
Confidence level of the intervals of
proportion_ci(default0.95): a number strictly between 0 and 1.- chisq_statistic
Statistic for
survey::svychisq():"F"(default),"Chisq","Wald","adjWald"or"saddlepoint"."saddlepoint"is refused on a replicate-weights design: survey computes its p-value without the denominator degrees of freedom there, so it comes out too small.- deff
Show the design effect of each percentage:
FALSE(default),TRUEor"replace".- df
Degrees of freedom for the intervals.
NULL(default) usessurvey::degf()on each domain. It does not reach the test:survey::svychisq()has nodfargument, so the Rao-Scott reference distribution keeps the design's own degrees of freedom and the note says so.- p_value
Show the p-value column (defaults to
TRUEwithby). A variable whose complete cases include negatively weighted rows is not tested: the Rao-Scott correction is a function of the design variance, which is not defined when the weights change sign. Its percentages are still reported, the note says which tests were withheld, and the call warns (spicy_negative_weights_no_test).- p_adjust
Multiple-comparison adjustment of the p-value column, applied to the family of every test in the table (one design-based p-value per variable; a withheld test stays out). One of
"none"(default),"holm","hochberg","hommel","bonferroni","BH"/"fdr", or"BY", as intable_regression(); delegated tostats::p.adjust(). Needsbyand the p-value column. See Multiple-comparison adjustment.- percent_base
The base of the percentages of a variable whose missing values the
(Missing)row shows (drop_na = FALSE), as intable_categorical()."valid"(the default) estimates them on the domain of the observed values of the variable, assurvey::svymean(na.rm = TRUE)does: the levels sum to 100, and the(Missing)row shows its count and no percentage, interval or design effect (blank cells,NAin the data frames and in tidy()). The intervals keep the degrees of freedom of their block, as underdrop_na = TRUE."total"estimates them on every row, the(Missing)row included, as this function did up to 0.14.1. Underby, the base is the observed values of each domain, theTotalblock and the column of missingbyvalues included. The test runs on the complete cases whatever the base. Without missing values to show (drop_na = TRUE, or a variable with none) the two bases give the same percentages. Unique abbreviations are accepted ("v","t").- percent_digits
Number of digits for percentages in report outputs. Defaults to
1. A whole number: a fraction is an error, as for every*_digitsargument.- p_digits
Integer >= 1. Number of decimal places used to render p-values in the
pcolumn (default:3, the APA Publication Manual standard). Both the displayed precision and the small-p threshold derive from this argument:p_digits = 3prints.045and<.001;p_digits = 4prints.0451and<.0001. Leading zeros are always stripped, following APA convention.- decimal_mark
The decimal mark, a single character:
"."(the default) or","in most styles; the Lancet style ofspicy_style()uses the middle dot. In the Excel sheet, a cell of one number shows the decimal separator of the reader's Excel (Excel output in spicy-package).- align
Horizontal alignment of the numeric columns:
"decimal"(the default),"center"or"right", as intable_continuous(), whose rendering engines this table shares, its Excel output included.- note
The note under the table.
NULL(the default) builds it: the general note, one paragraph opened by the lead-in of the style ("Note." by default, none under thejamaandlancetthemes; seenote_labelinspicy_style()), then, in atable_regression()withstars, the legend of the stars on a line of its own. A single string replaces the general note, the sentences the table writes about its data included. It is printed as typed, line breaks ("\n") included, after the lead-in of the style, which a string opening with a lead-in of its own does not repeat (note = "Note. Data weighted."), and the legend of the stars stays below it.""keeps that legend alone, and no note at all without stars.FALSEremoves the note from every output, the legend included.- note_add
Sentences to add to the note: a character vector of one or more strings, each printed as typed (no period is added) and joined to the note by a space. They close its paragraph, after the definitions of the abbreviations and before the legend of the stars, in every output and in
attr(x, "note"), and the sentences the table writes stay. With a string innote, they follow it, so a wrapper can add a house sentence to every table while one table replaces its note. AnNAor an empty string is an error, and so isnote_addwithnote = FALSE, which leaves no note to add to.- output
One of
"default","data.frame","long", or a rendering engine:"tinytable","gt","flextable","excel","clipboard","word"."data.frame"is the displayed table with its numbers,"long"one row per variable, level and group, as intable_categorical(); see Value.- indent_text
Prefix used for modality labels in report table building. Defaults to
" "(two spaces).- indent_text_excel_clipboard
Stronger indentation used in Excel and clipboard exports. Defaults to six non-breaking spaces.
- excel_path
Path for
output = "excel", ending in".xlsx", in a directory that exists. Defaults toNULL. A file already at that path is replaced: each call writes a new workbook.- excel_sheet
Sheet name for Excel export.
NULL(the default) uses"Categorical". The workbook holds this one sheet: a second call with the sameexcel_pathreplaces the file and does not add a sheet.- clipboard_delim
Delimiter for clipboard text export. Defaults to
"\t". A cell holding the delimiter itself, a double quote or a line break is quoted RFC 4180-style, so the grid survives whatever delimiter you choose.- word_path
File path for
output = "word", ending in".docx", in a directory that exists. Defaults toNULL.- word_template
Optional path to a custom .docx file used as the template for
output = "word". The template's header, footer, page size, margins, and named styles ("Table Caption" in particular) are honored; the table is appended to the template body. Useful for institutional templates with pre-set headers ("APA Style", "Manuscript Submission Template", etc.). DefaultNULL(uses flextable's stock template).Customizing the caption appearance: the table caption is tagged with the Word named style
"Table Caption". The visual rendering (italic / bold / color / font) follows whatever that style is set to in the docx template. The stock Word template renders"Table Caption"in italic, the type of the APA table title (APA Manual 7 section 7.11, p. 201), where the APA puts the bold table number on its own line above it (section 7.10, p. 200). For a different appearance (Nature-style bold non-italic, APA-strict 2-line bold-number / italic-title, etc.), edit the"Table Caption"style in a docx template and pass it viaword_template = "your_template.docx". Style-based delegation keeps the rendered caption consistent with the surrounding document and lets editorial conventions (Nature, APA-strict, journal-specific) be applied without modifying the call site.- user_na
Logical. If
TRUE(the default), declared missing values in the row variables and inbyare treated as missing: they join the"(Missing)"level underdrop_na = FALSE, and underdrop_na = TRUEthey are removed with a dedicated disclosure line (Declared missing values removed: ...). IfFALSE, the declared codes stay valid categories. See the "Declared missing values" section offreq().- style
A journal style: a theme name (
"jama","nejm","lancet","annals","apa","aer"), aspicy_style()object, orNULL(the default). A style only changes DEFAULTS – any argument you pass explicitly wins over it. Setoptions(spicy.style = )for document-wide scope. A theme covers numeric formatting, the word that opens the note and the abbreviations the note defines, not full editorial conformity;?spicy_stylelists the exact rules each one encodes and the official document they come from. An unknown name is an error.
Value
Depends on output:
"default": aspicy_categorical_svy_table(adata.framesubclass, with the parent class"spicy_table"), printed when the call is bare; its columns are the table's compute frame, internal and liable to change without notice, and the display frame and the typed view are attached."data.frame": the displayed table with its numbers, what as.data.frame() of the default object returns: one row per printed row (the header row of each variable, which carries its p-value, then its levels), the key columnsvariable(the column name),label(the label displayed),leveland.row_role("factor_header","level", or"missing"on the row of missing values the table adds), then one column per displayed column, in their order, the name of a column of a block joining the block printed above it to the header printed under it: per block ofby(and theTotalmargin)<group> n,<group> %, withproportion_cithe interval bounds<group> 95% CI LLand<group> 95% CI UL(the level ofci_level, as printed), withdeff<group> DEff, and lastp. Withoutby, the columns of the one block aren,%, ..."long": one row per variable, level and group, in the order of the table, withvariable,label,level,.row_role(the role oflevel:"level", or"missing"), withbygroup,.group_role(the role ofgroup:"group","missing"for the column of missingbyvalues, or"total") andtotal(TRUEon the rows of the margin), thenn(observed),pct(the estimated percentage),ci_lower,ci_upper(its interval,NAwithoutproportion_ci),deff(NAwithoutdeff), and, withbyand the p-value,test_type(the statistic ofsurvey::svychisq(),chisq_statistic),p.valueand, underp_adjust,p_unadjusted."tinytable","gt","flextable": the rendered table."excel"/"word": writes the file and returns its path invisibly."clipboard": copies the table and returns the displaydata.frameinvisibly.
The default object and the two data frames carry the whole note as
printed, its lead-in included, in attr(x, "note"), and the base of
their percentages in attr(x, "percent_base"), "valid" or "total"
(see percent_base). The default object also keeps the title the
console prints, in attr(x, "title").
tidy() reports the proportions
between 0 and 1.
What the columns are
n is the observed count – the number of rows in the sample, not
an estimated population size. % is the estimated percentage
within its column: without by it is the distribution of the
variable in the population, with by the distribution inside that
domain, on the observed values of the variable unless
percent_base = "total". The table note gives the sample size (the
rows of non-zero weight, which the n columns count, as
survey::unwtd.count() does) and the estimated population together,
because neither alone tells the reader what they are looking at.
spicy_style(sample_size = "header") heads each domain with its
unweighted count as well, "E (n = 144)", the Total column with N, and
keeps that sentence; sample_size = "none" leaves it out (see
spicy_style()).
proportion_ci = TRUE adds the interval of each percentage.
ci_method chooses among the seven survey::svyciprop() offers;
the default "logit" is bounded inside 0 to 100, which the Wald
interval ("mean") is not. The percentage itself always comes from
survey::svymean(), so it does not move when ci_method does.
A percentage of 0 or 100 has no design-based interval: its estimated
variance is zero. Whatever ci_method, such a cell gets the exact
binomial (Clopper-Pearson) interval on the unweighted count of its
column, with no degrees-of-freedom factor. This is the rule of Korn
and Graubard (1998, p. 194) for an estimate of 0, which the NCHS data
presentation standards for proportions apply to its complement as well
(Parker et al. 2017, pp. 2-3). The note says so when such a cell is
shown.
A cell that survey cannot estimate, most often because a stratum holds
a single primary sampling unit under its default
options(survey.lonely.psu = "fail"), shows a dash: the function
warns once, quoting survey's messages (class
spicy_svy_estimation_failed), and the note says what the dash means.
A warning of survey's own, such as the one on a stratum with a single
primary sampling unit in a domain under
options(survey.adjust.domain.lonely = TRUE), is said once per table,
with the number of times survey raised it.
The test
svychisq() with chisq_statistic = "F" (the default) is the
Pearson chi-square with the Rao-Scott second-order correction,
referred to F(ndf, survey::degf(design)). It is survey's own
default and the one Stata's svy: tabulate reports. The design-based
test has no exact counterpart, so the switch to Fisher's exact test
that test makes in table_categorical() when an expected count is
below 5 has no equivalent here.
It runs on the complete cases of the two variables, and on their
observed levels: a (Missing) row and a declared-but-unobserved
level are descriptive, and neither belongs to the null hypothesis.
The p-value is therefore the same whether drop_na shows those rows
or removes them, and the intervals beside it describe the same
domain – the two families test the same table.
"Chisq" shows the p-value only: survey adjusts the statistic in
the "F" branch and only the p-value in the "Chisq" one, so the
statistic there is not the one the p-value came from. "Wald",
"adjWald" and "saddlepoint" are available; "lincom" and
"wls-score" are refused, the first because its integration is
documented as failing in the far tail (?pchisqsum), the second
because it has no reporting convention here.
Groups with no data
As in table_categorical(), a variable with no observed value in a
group of by that holds sampled rows, typically a question not asked
in that group, has no data there, which is not a missing answer. Its
cells in that group show an en dash (NA in the data frames, in
tidy() and in as_structured()),
and its rows there are left out of everything computed for that
variable: the missing values the note counts, the Total block, the
(Missing) row and the test. A variable left with fewer than two
groups with data, or observed at one level, is not tested: its p
cell shows the dash, the undefined cell. The note
says "No data for X in G.", in one sentence for the variables with no
data in the same groups ("No data for X and Y in G."). Without by, a
variable with no observed value at all keeps its declared levels (its
one row when it declares none) with the dash, and the note says "No
data for X."
Stability
This function is stabilizing in the sense ?spicy defines: the
names of its design-specific arguments may still be tightened
before 1.0 – with a NEWS.md entry – but the behavior does not
change silently. It was experimental through 0.13; the shape of the
table has held across the cycle, so it now moves on the parent
family's clock rather than its own. The numbers themselves are
survey's and do not move with it.
What is absent, and why
weights and rescale (the weighting is the design). correct
(Yates), simulate_p and simulate_B, which have no meaning once
the reference distribution is Rao-Scott's. percent, not yet: a row
percentage is estimated within its level, a domain of its own, so every
level of every variable would bring its own degrees of freedom,
intervals and design effects. And the association
measures: Cramér's V, phi, tau-b/c, gamma, Somers' D and lambda
have no established design-based variance, and the intervals
table_categorical() gives them assume simple random sampling. The
design-based measure of association here is the Rao-Scott test in
the p column; for an effect size, model it with
table_regression(survey::svyglm(...)).
Multiple-comparison adjustment
The p-values of a descriptive table describe: they test no
prespecified hypothesis. STROBE (explanation of item 14) advises
against significance tests in descriptive tables, hence the default
p_adjust = "none".
When a journal or a protocol asks for adjusted p-values anyway,
p_adjust applies stats::p.adjust() to the family of every test in
the table: one p-value per variable (one per block in
table_outcome()), never the rows of one variable, which share one
test. "holm" suits a confirmatory set of comparisons, "BH" a
screening one; table_regression() lists the methods. A test that
returned no p-value stays out of the family.
The adjustment runs before any formatting, so the p column and its
<.001 threshold show the adjusted values, and the table note gives
the number of tests and the method. The raw p-values stay in the
object: a p_unadjusted column next to the p-value column of the
returned data frames, and col_meta$p$p_unadjusted (with the method
in p_adjust and the family size in p_adjust_m) in
as_structured(). Without by, or with p_value = FALSE, the table
shows no p-value to adjust, and a p_adjust other than "none" is an
error.
References
American Psychological Association. (2020). Publication manual of the American Psychological Association (7th ed.). doi:10.1037/0000165-000
Korn, E. L., & Graubard, B. I. (1998). Confidence intervals for proportions with small expected number of positive counts estimated from survey data. Survey Methodology, 24(2), 193-201.
Parker, J. D., Talih, M., Malec, D. J., et al. (2017). National Center for Health Statistics data presentation standards for proportions. Vital and Health Statistics, Series 2, No. 175.
Vandenbroucke, J. P., von Elm, E., Altman, D. G., Gøtzsche, P. C., Mulrow, C. D., Pocock, S. J., Poole, C., Schlesselman, J. J., & Egger, M. (2007). Strengthening the reporting of observational studies in epidemiology (STROBE): Explanation and elaboration. PLoS Medicine, 4(10), e297. doi:10.1371/journal.pmed.0040297
See also
table_categorical() for the data-frame sibling,
table_continuous_svy() for continuous variables.
Examples
data(api, package = "survey")
dclus1 <- survey::svydesign(
id = ~dnum, weights = ~pw, data = apiclus1, fpc = ~fpc
)
table_categorical_svy(dclus1, select = c(stype, awards))
#> Categorical table
#>
#> Variable │ n %
#> ────────────┼───────────────
#> stype │
#> E │ 144 78.7
#> H │ 14 7.7
#> M │ 25 13.7
#> ╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌
#> awards │
#> No │ 53 29.0
#> Yes │ 130 71.0
#>
#> Note. N = 183 (weighted 6194). Design: cluster (dnum), 15 PSUs, with finite population correction; 14 degrees of freedom. Std. errors: design-based (Taylor linearization). Confidence intervals and tests use the design degrees of freedom. % = estimated percentage. n = observed (unweighted) count.
table_categorical_svy(dclus1, select = stype, by = sch.wide)
#> Categorical table by sch.wide
#>
#> No Yes Total
#> ──────────── ───────────── ─────────────
#> Variable │ n % n % n % p
#> ────────────┼────────────────────────────────────────────────────
#> stype │ .022
#> E │ 12 52.2 132 82.5 144 78.7
#> H │ 3 13.0 11 6.9 14 7.7
#> M │ 8 34.8 17 10.6 25 13.7
#>
#> Note. N = 183 (weighted 6194). Percentages are column percentages. Design: cluster (dnum), 15 PSUs, with finite population correction; degrees of freedom vary by group (9–14). Std. errors: design-based (Taylor linearization). Confidence intervals and tests use the design degrees of freedom. P-value: design-based Pearson chi-squared (Rao-Scott second-order correction). % = estimated percentage. n = observed (unweighted) count.
table_categorical_svy(
dclus1,
select = stype,
proportion_ci = TRUE,
deff = TRUE
)
#> Categorical table
#>
#> 95% CI
#> ──────────────
#> Variable │ n % LL UL DEff
#> ────────────┼───────────────────────────────────────
#> stype │
#> E │ 144 78.7 67.1 87.0 2.40
#> H │ 14 7.7 3.5 15.8 1.91
#> M │ 25 13.7 8.4 21.3 1.40
#>
#> Note. N = 183 (weighted 6194). Design: cluster (dnum), 15 PSUs, with finite population correction; 14 degrees of freedom. Std. errors: design-based (Taylor linearization). Confidence intervals and tests use the design degrees of freedom. Percentage CIs: Wald on the logit scale (logistic regression). % = estimated percentage. n = observed (unweighted) count. CI = confidence interval; LL = lower limit; UL = upper limit; DEff = design effect.