Produces a formatted attrition table from a cf_flow object. Three output
backends are supported: "flextable" (best for Word), "gt" (best for
HTML and LaTeX), and "huxtable". The underlying data is built by
as_attrition_tibble(), which you can call directly for custom formatting.
Usage
as_attrition_table(
flow,
backend = c("flextable", "gt", "huxtable"),
show_categories = TRUE,
assessed_label = "Assessed for eligibility",
final_label = "Final cohort",
digits = 1L,
criterion_col_label = "Criterion",
n_col_label = "N",
removed_col_label = "Removed",
pct_col_label = "% removed",
consequential_col_label = "Consequential",
branch_by = NULL,
count_by = NULL,
branch_na_label = "Missing",
group_x = NULL,
group_y = NULL,
group_x_label = NULL,
group_y_label = NULL,
group_na_label = "Missing",
levels = character(0),
level_labels = NULL,
show_consequential = NULL,
shade = NULL,
shade_fn = NULL,
shade_palette = c("#FFFFFF", "#F8696B")
)Arguments
- flow
A
cf_flowobject produced byapply_criteria().- backend
Character string:
"flextable"(default),"gt", or"huxtable".- show_categories
Logical. When
TRUE(default) steps with the samecategoryare collapsed under a single parent row. WhenFALSEone row per step is produced.- assessed_label
Character string for the header row. Default
"Assessed for eligibility".- final_label
Character string for the trailing final-cohort row. Default
"Final cohort".- digits
Integer. Number of decimal places for
pct_removed. Default1. Formatted tables and diagrams keep trailing zeros ("10.0%").- criterion_col_label
Column header for the criterion/label column. Default
"Criterion".- n_col_label
Column header for the N column. Default
"N".- removed_col_label
Column header for the removed column. Default
"Removed".- pct_col_label
Column header for the percentage column. Default
"% removed".- consequential_col_label
Column header for the optional "consequential" column shown per level when
levelsis supplied andshow_consequentialresolves toTRUE. Default"Consequential".- branch_by
Optional column name (string) for allocation branching. When
NULL(default), the table has a singlencolumn unless the pipeline has arandomise()step, in which case itsarmscolumn is used automatically. When supplied (or defaulted), the surviving cohort is split by this column and the final row's total is broken out into one additional column per branch value (named after the branch value, e.g.Control,Intervention), each populated only on the final row. Usefinal_label = "Randomised"when appropriate. Cannot be combined withgroup_x/group_y. Rows whose branch value isNAform their own branch, labelledbranch_na_label.- count_by
Optional hierarchy level to count instead of rows: a level name from the flow's
cf_hierarchy(), or the column of a single-column level (e.g."participant_id"). Every count (n,n_removed,pct_removedand the branch columns) is then the number of distinct units, and a unit counts as removed at the step where it loses its last row. Essential for crossover and other designs with several rows per participant. Requiresapply_criteria(hierarchy = ); without a hierarchy, or with a column that is not a level, it errors and says how to fix the call. (Before cohortflow 0.0.0.9016count_bytook any column and changed only the branch columns, leavingncounting rows.)- branch_na_label
Character string used to label the branch formed by
NAvalues inbranch_by(and, inas_consort_diagram(), the stage formed byNAvalues instage_by). Default"Missing". Ignored when the column has noNAvalues.- group_x
Optional column name (string), present in
flow$data, used to repeat the attrition table across the "column" direction (e.g. trial site). See the Grouping section.- group_y
Optional column name (string), present in
flow$data, used to repeat the attrition table across the "row" direction (e.g. time period). See the Grouping section.- group_x_label
Optional prefix label for
group_xcolumn headings (e.g."Site"to show"Site: A"). DefaultNULL(show the group value alone).- group_y_label
Optional prefix label for
group_yrow headings (e.g."Period"to show"Period: 1"). DefaultNULL(show the group value alone).- group_na_label
Character string used to label the group formed by
NAvalues ingroup_x/group_y(see the Grouping section). Default"Missing". Ignored when the corresponding grouping column has noNAvalues.- levels
Optional; requires
flowto have been built withapply_criteria(hierarchy = ...). When the defaultcharacter(0), this argument is ignored and the row-count behaviour above is unchanged. WhenNULL, one stacked block per hierarchy level is returned (finest to coarsest), each with alevelcolumn and an additionaln_consequentialcolumn (seeapply_criteria()'shierarchyargument for the counting rule). When a character vector of level name(s), only those levels are returned, in the order given. Cannot be combined withgroup_x/group_y,branch_by, orcount_by. A row with anNAin any of a level's columns is not a unit at that level, but still counts at every level whose own key is complete: an expected participant with no cluster is one participant at risk and zero clusters.- level_labels
Optional display names for the column blocks produced by
levels. Either a vector positionally aligned withlevels, or a vector named by level (e.g.c(trial = "Trials", participant = "Participants")). DefaultNULL, which uses the level names as-is – level names are user-chosen and are not auto-pluralised or title-cased, since guessing would be as likely to surprise as to help; supplylevel_labelsto get "Trials" from a level namedtrial. Ignored unlesslevelsis supplied.- show_consequential
Logical, or
NULL(default). Controls whether an extra "consequential" column is shown per level, reporting units lost only because agroup_include()/group_exclude()group they belonged to was removed (seelevelsonas_attrition_tibble()). WhenNULL, the column is included only if the underlying data has any non-zero value for it, so pipelines without group-level criteria render unchanged. Ignored unlesslevelsis supplied.- shade
Optional character string:
"pct_removed"or"n_removed". When supplied, shades the N/Removed/% cells of step and category rows with an automatic colour gradient based on that column's value. DefaultNULL(no shading).- shade_fn
Optional function for custom cell shading; see the Shading section. Default
NULL.- shade_palette
Character vector of >= 2 colours defining the gradient used by
shade. Defaultc("#FFFFFF", "#F8696B")(white to red).
Value
A flextable, gt_tbl, or huxtable object, ready to print or
include in a document. When branch_by is supplied, one additional
column per branch value is added after the percentage column, headed
with the branch value itself and populated only on the final row. When
group_x/group_y are supplied, the table is a repeated grid as
described in the Grouping section. When levels is supplied, the table
has one N/Removed/% column block per level, as described in the
Hierarchy levels section.
Output formats
"flextable"– uses the flextable and officer packages. Renders natively to Word (.docx) viaofficer::read_docx(), to PDF viaflextable::save_as_image(), and to HTML. Best choice when Word is the primary target."gt"– uses the gt package. Renders to HTML (gt::gtsave(..., "table.html")), LaTeX (gt::as_latex()), and Word (viagt::gtsave(..., "table.docx")requires the webshot2 package). Best choice when LaTeX or HTML is the primary target."huxtable"– uses the huxtable package. Supports Word, LaTeX, and HTML output.
Grouping (group_x / group_y)
Supplying group_x and/or group_y repeats the whole attrition table
across a grid: group_x values become repeated column blocks (N /
Removed / % removed, headed by a spanning column group), and group_y
values become repeated row blocks (each preceded by a bold group-heading
row), so the criterion rows appear once but attrition counts are shown
per group combination. This is useful, for example, for showing a
stepped-wedge trial's attrition by site (group_x) and period
(group_y). branch_by cannot be combined with grouping.
Shading
Cells can be shaded to highlight high-attrition rows/cells:
shade = "pct_removed"or"n_removed"applies an automatic colour gradient (shade_palette, default white to red) scaled across the values present in step/category rows.shade_fngives full control: supply a function that takes the attrition tibble (as returned byas_attrition_tibble(), includinggroup_x/group_ycolumns when grouped) and returns a character vector of colours (orNA) the same length as the tibble, one colour per row.shade_fntakes precedence overshadeif both are supplied.
Hierarchy levels (levels)
Supplying levels repeats the N / Removed / % removed columns once per
hierarchy level, so a single criterion row reports its effect at every
level side by side – the reporting form required by the CONSORT cluster
extension (Campbell, Elbourne & Altman, BMJ 2004;328:702-8) and the
within-person extension, where losses at each stage are counted at both
the unit of analysis and the unit of recruitment. For example, with a
cluster-randomised trial where participants nest inside clusters:
h <- cf_hierarchy(participant = "participant_id", cluster = "cluster_id")
flow <- apply_criteria(dat, crit, hierarchy = h)
as_attrition_table(
flow,
levels = c("participant", "cluster"),
level_labels = c(participant = "Participants", cluster = "Clusters")
)produces one row per criterion with a column block for participants and a
column block for clusters, e.g. "Cluster too small – 42 participants
removed, 3 clusters removed". Shading (shade/shade_fn) is computed
per level – each level's colour gradient is scaled across that level's
own values, not across all levels combined. levels cannot be combined
with group_x/group_y/branch_by/count_by. Rows with an NA in a
level's column(s) are not counted as units at that level (they still count
at any level whose own key is complete).
See also
as_attrition_tibble() for the underlying plain-tibble data layer.
Other reporting:
as_attrition_tibble(),
as_characteristics_table(),
as_characteristics_tibble(),
as_consort_diagram(),
as_narrative(),
save_consort_diagram()
Examples
# \donttest{
dat <- mock_parallel_rct(n_participants = 200, seed = 1)
crit <- cf_criteria() |>
include(~ !is.na(age), label = "Age recorded", category = "Valid age") |>
include(~ age >= 18, label = "Adults only", category = "Valid age") |>
include(~ eligible_screen, label = "Passed screening") |>
include(~ !is.na(consent_date), label = "Consent recorded", category = "Consent") |>
exclude(~ withdrew, label = "Withdrew consent", category = "Consent")
flow <- apply_criteria(dat, crit)
#> No `id` supplied and no `.cf_row_id` column found. Adding a sequential `.cf_row_id`.
if (requireNamespace("flextable", quietly = TRUE) &&
requireNamespace("officer", quietly = TRUE)) {
as_attrition_table(flow) # flextable (Word-ready)
as_attrition_table(flow, shade = "pct_removed") # shade by % removed
}
Criterion
N
Removed
% removed
Assessed for eligibility
200
Valid age
200
16
8.0%
Age recorded
200
10
5.0%
Adults only
190
6
3.0%
Passed screening
184
15
8.2%
Consent
169
33
19.5%
Consent recorded
169
26
15.4%
Withdrew consent
143
7
4.1%
Final cohort
136
68.0% included
if (requireNamespace("gt", quietly = TRUE)) {
as_attrition_table(flow, backend = "gt") # gt (LaTeX/HTML-ready)
}
if (requireNamespace("huxtable", quietly = TRUE)) {
as_attrition_table(flow, backend = "huxtable") # huxtable
}
#> ──────────────────────────────────────────────────────
#> Criterion N Removed % removed
#> ──────────────────────────────────────────────────────
#> Assessed for 200
#> eligibility
#> Valid age 200 16 8.0%
#> Age recorded 200 10 5.0%
#> Adults only 190 6 3.0%
#> Passed screening 184 15 8.2%
#> Consent 169 33 19.5%
#> Consent recorded 169 26 15.4%
#> Withdrew consent 143 7 4.1%
#> ──────────────────────────────────────────────────────
#> Final cohort 136 68.0% included
#> ──────────────────────────────────────────────────────
#>
#> Column names: label, n, n_removed, pct_removed
if (requireNamespace("flextable", quietly = TRUE) &&
requireNamespace("officer", quietly = TRUE)) {
# Grid: sites as columns, periods as rows (stepped-wedge design)
sw <- mock_stepped_wedge(n_participants = 400, n_periods = 4, seed = 1)
flow_sw <- apply_criteria(sw, crit, id = "event_id")
as_attrition_table(flow_sw, group_x = "site_id", group_y = "period")
# Hierarchy levels: cluster CONSORT reporting
cl <- mock_cluster_rct(n_clusters = 20, seed = 1)
h <- cf_hierarchy(participant = "participant_id", cluster = "cluster_id")
flow_cl <- apply_criteria(cl, crit, id = "participant_id", hierarchy = h)
as_attrition_table(flow_cl, levels = c("participant", "cluster"))
}
participant
cluster
Criterion
N
Removed
% removed
N
Removed
% removed
Assessed for eligibility
480
17
Valid age
480
36
7.5%
17
—
—
Age recorded
480
24
5.0%
17
—
—
Adults only
456
12
2.5%
17
—
—
Passed screening
444
44
9.9%
17
—
—
Consent
400
81
20.2%
17
1
5.9%
Consent recorded
400
70
17.5%
17
1
5.9%
Withdrew consent
330
11
2.8%
16
—
—
Final cohort
319
66.5% included
16
94.1% included
# }
if (FALSE) { # \dontrun{
# Save to Word
ft <- as_attrition_table(flow)
flextable::save_as_docx(ft, path = "attrition.docx")
} # }