| Title: | Define and Apply Cohort Inclusion/Exclusion Criteria |
|---|---|
| Description: | Define inclusion and exclusion criteria for cohort studies using formulas or functions, apply them to data, and render the resulting attrition flow as CONSORT flow diagrams, tables, or narrative text. Supports hierarchical designs (participants nested in clusters/sites) and flexible grouping for reporting. Criteria pipelines can be serialised to YAML for reproducibility and sharing. Parts of this package were developed with the assistance of AI coding assistants (GitHub Copilot and Claude Code, using Claude models from Anthropic); see the LLM use statement on the package website. |
| Authors: | Matthew Moore [aut, cre] (ORCID: <https://orcid.org/0000-0003-0730-8027>), Health Research Council of New Zealand [fnd] |
| Maintainer: | Matthew Moore <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.0.0.9017 |
| Built: | 2026-11-24 02:39:10 UTC |
| Source: | https://github.com/mattmoo/cohortflow |
Evaluates each step in a cf_criteria pipeline cumulatively against a data
frame, recording which rows are removed at each step. Returns a cf_flow
object from which the surviving cohort (cohort()) and excluded rows
(excluded()) can be extracted.
apply_criteria( data, criteria, id = NULL, expected = NULL, by = NULL, hierarchy = NULL )apply_criteria( data, criteria, id = NULL, expected = NULL, by = NULL, hierarchy = NULL )
data |
A data frame. |
criteria |
A |
id |
One or more column names (character vector) to use as the row
identifier; supply more than one for a composite (multi-column) key. If
|
expected |
Optional data frame (typically built with |
by |
Column name(s) shared by |
hierarchy |
Optional |
Before any step is evaluated, check_criteria() verifies that every step
refers only to columns present in data (after any expected join).
A cf_flow object.
apply_criteria() needs a stable row identifier to track exclusions. By
default it looks for a .cf_row_id column in data. If one is not found
and id is NULL, a sequential integer identifier is added automatically
(with a message). Supply id to use an existing column as the identifier.
The identifier (whether supplied via id or a pre-existing .cf_row_id
column) must uniquely identify every row: it may contain neither
duplicates nor NA values, and apply_criteria() aborts if it does. For
designs with several rows per participant (e.g. crossover or stepped-wedge
data), use a row-level identifier such as event_id, not the participant
identifier.
| Type | Predicate | Effect |
include |
Row-wise logical vector | Keep TRUE rows |
exclude |
Row-wise logical vector | Drop TRUE rows |
group_include |
Per-group scalar (summarise context) | Keep rows in groups where result is TRUE |
group_exclude |
Per-group scalar (summarise context) | Drop rows in groups where result is TRUE |
select_within |
Per-group logical vector | Keep TRUE rows within each group |
randomise |
None (predicate = NULL) |
Records the randomisation unit and arm column for downstream reporting |
Rows whose by value is NA cannot be assigned to a group and are always
removed by grouped step types (group_include, group_exclude,
select_within).
Other pipeline:
cf_expected(),
cf_hierarchy(),
continue_criteria()
dat <- mock_cluster_rct(n_participants = 200, seed = 1) crit <- cf_criteria() |> include(~ eligible_screen, label = "Passed screening") |> include(~ !is.na(consent_date), label = "Consent recorded", category = "Consent") |> exclude(~ withdrew, label = "Withdrew consent", category = "Consent") |> group_include(by = "cluster_id", ~ n() >= 5, label = "Cluster size >= 5") flow <- apply_criteria(dat, crit) flow cohort(flow) excluded(flow)dat <- mock_cluster_rct(n_participants = 200, seed = 1) crit <- cf_criteria() |> include(~ eligible_screen, label = "Passed screening") |> include(~ !is.na(consent_date), label = "Consent recorded", category = "Consent") |> exclude(~ withdrew, label = "Withdrew consent", category = "Consent") |> group_include(by = "cluster_id", ~ n() >= 5, label = "Cluster size >= 5") flow <- apply_criteria(dat, crit) flow cohort(flow) excluded(flow)
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.
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") )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") )
flow |
A |
backend |
Character string: |
show_categories |
Logical. When |
assessed_label |
Character string for the header row. Default
|
final_label |
Character string for the trailing final-cohort row.
Default |
digits |
Integer. Number of decimal places for |
criterion_col_label |
Column header for the criterion/label column.
Default |
n_col_label |
Column header for the N column. Default |
removed_col_label |
Column header for the removed column.
Default |
pct_col_label |
Column header for the percentage column.
Default |
consequential_col_label |
Column header for the optional
"consequential" column shown per level when |
branch_by |
Optional column name (string) for allocation branching.
When |
count_by |
Optional hierarchy level to count instead of rows: a level
name from the flow's |
branch_na_label |
Character string used to label the branch formed by
|
group_x |
Optional column name (string), present in |
group_y |
Optional column name (string), present in |
group_x_label |
Optional prefix label for |
group_y_label |
Optional prefix label for |
group_na_label |
Character string used to label the group formed by
|
levels |
Optional; requires |
level_labels |
Optional display names for the column blocks produced
by |
show_consequential |
Logical, or |
shade |
Optional character string: |
shade_fn |
Optional function for custom cell shading; see the
Shading section. Default |
shade_palette |
Character vector of >= 2 colours defining the
gradient used by |
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.
"flextable" – uses the flextable and officer packages.
Renders natively to Word (.docx) via officer::read_docx(), to PDF
via flextable::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 (via gt::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.
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.
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_fn gives full control: supply a function that takes the
attrition tibble (as returned by as_attrition_tibble(), including
group_x/group_y columns when grouped) and returns a character
vector of colours (or NA) the same length as the tibble, one colour
per row. shade_fn takes precedence over shade if both are supplied.
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).
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()
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) 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 } 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 } 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")) } ## Not run: # Save to Word ft <- as_attrition_table(flow) flextable::save_as_docx(ft, path = "attrition.docx") ## End(Not run)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) 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 } 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 } 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")) } ## Not run: # Save to Word ft <- as_attrition_table(flow) flextable::save_as_docx(ft, path = "attrition.docx") ## End(Not run)
Produces a flat tibble describing the attrition at each step (or category)
of a cohort flow pipeline. This is the underlying data layer used by
as_attrition_table(), and is also useful for custom formatting.
as_attrition_tibble( flow, show_categories = TRUE, assessed_label = "Assessed for eligibility", final_label = "Final cohort", digits = 1L, branch_by = NULL, count_by = NULL, group_x = NULL, group_y = NULL, group_na_label = "Missing", levels = character(0), branch_na_label = "Missing" )as_attrition_tibble( flow, show_categories = TRUE, assessed_label = "Assessed for eligibility", final_label = "Final cohort", digits = 1L, branch_by = NULL, count_by = NULL, group_x = NULL, group_y = NULL, group_na_label = "Missing", levels = character(0), branch_na_label = "Missing" )
flow |
A |
show_categories |
Logical. When |
assessed_label |
Character string for the header row. Default
|
final_label |
Character string for the trailing final-cohort row.
Default |
digits |
Integer. Number of decimal places for |
branch_by |
Optional column name (string) for allocation branching.
When |
count_by |
Optional hierarchy level to count instead of rows: a level
name from the flow's |
group_x |
Optional column name (string), present in |
group_y |
Optional column name (string), present in |
group_na_label |
Character string used to label the group formed by
|
levels |
Optional; requires |
branch_na_label |
Character string used to label the branch formed by
|
A tibble::tibble() with columns:
row_type"header", "category", "step", or "final"
labelDisplay text for the row
indent_level0 = header/final, 1 = category or top-level
step, 2 = sub-step under a category
nNumber of participants at this point (N entering for category/step rows; N surviving for the final row)
n_removedNumber removed at this step (NA for header/final)
pct_removedPercentage removed relative to entering N (NA for
header; for final row: percentage retained of original N)
When branch_by is supplied, one additional column per unique branch
value is appended (named after the branch value), populated only on the
final row with that branch's surviving count. When group_x/group_y
are supplied, group_x and group_y character columns are appended (see
the Grouping section) and the tibble contains one stacked block per group
combination rather than a single block. When the pipeline has a
randomise() step, a post_randomisation logical column is appended
(TRUE for header/final/step/category rows at or after that step,
FALSE before it); this column is omitted entirely when there is no
randomise() step, so existing pipelines see no schema change.
The tibble always starts with an "assessed" header row and ends with a
"final cohort" row. When show_categories = TRUE (the default), steps
that share a category are collapsed into a parent row (indent level 1)
with individual step sub-rows (indent level 2) nested beneath it.
Uncategorised steps appear at indent level 1 without sub-rows. When
show_categories = FALSE, one row per step is produced at indent level 1.
Steps are collapsed under a category only when they are consecutive in the pipeline (reordering steps would change the cumulative counts). A category whose steps are separated by other steps therefore produces more than one category row, and a warning suggests reordering the pipeline.
pct_removed: percentage of entering N removed at this row's step (or
category). For the final cohort row this is the percentage retained
relative to the initial N (i.e. n / n_start * 100).
Percentages are relative to n_in – the number entering that step or,
for a category row, the number entering the first step in that category.
When steps are grouped under a category (show_categories = TRUE),
each step sub-row's pct_removed is also expressed relative to the
category's total entering N (rather than its own, progressively
smaller, entering N), so that all rows within a category share the same
denominator and sum consistently with the category row's percentage.
group_x / group_y)When group_x and/or group_y are supplied, the criteria pipeline
stored in flow is re-applied independently to each subset of the
original data defined by the unique values of the grouping column(s)
(e.g. trial site, time period). The returned tibble is a flat, "long"
stack of one full attrition block per group combination, with additional
group_x and group_y character columns identifying which subset each
row belongs to (NA for the ungrouped dimension). This long format is
the input to the grid layout produced by as_attrition_table(); use it
directly if you want to build your own custom cross-tabulated output.
branch_by/count_by cannot currently be combined with grouping.
Rows where the grouping column itself is NA (e.g. missing ethnicity)
are not silently dropped, and are never folded into every other
group's counts. Instead they form their own explicit group, labelled by
group_na_label (default "Missing"), so the grouped totals still sum
to the full dataset.
as_attrition_table() for formatted table output.
Other reporting:
as_attrition_table(),
as_characteristics_table(),
as_characteristics_tibble(),
as_consort_diagram(),
as_narrative(),
save_consort_diagram()
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", category = "Eligible at screening") |> include(~ !is.na(consent_date), label = "Consent recorded", category = "Consent") |> exclude(~ withdrew, label = "Withdrew consent", category = "Consent") flow <- apply_criteria(dat, crit, id = "participant_id") as_attrition_tibble(flow)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", category = "Eligible at screening") |> include(~ !is.na(consent_date), label = "Consent recorded", category = "Consent") |> exclude(~ withdrew, label = "Withdrew consent", category = "Consent") flow <- apply_criteria(dat, crit, id = "participant_id") as_attrition_tibble(flow)
Formats as_characteristics_tibble() as a publication-ready table in the
same APA style and through the same backends as as_attrition_table():
a bold heading row per variable, indented summary rows, one column per
step headed by the step label and its n.
as_characteristics_table( flow, vars, backend = c("flextable", "gt", "huxtable"), steps = NULL, excluded = FALSE, level = NULL, numeric = "mean_sd", missing = c("ifany", "always", "never"), digits = 1L, drop_randomise = TRUE, assessed_label = "Assessed for eligibility", missing_label = "Missing", variable_col_label = "Characteristic", var_labels = NULL )as_characteristics_table( flow, vars, backend = c("flextable", "gt", "huxtable"), steps = NULL, excluded = FALSE, level = NULL, numeric = "mean_sd", missing = c("ifany", "always", "never"), digits = 1L, drop_randomise = TRUE, assessed_label = "Assessed for eligibility", missing_label = "Missing", variable_col_label = "Characteristic", var_labels = NULL )
flow |
A |
vars |
Character vector of column names to summarise. |
backend |
Character string: |
steps |
Optional step selectors (a vector or list); see the section
"Steps". |
excluded |
Logical. |
level |
Optional hierarchy level name at which to count units; see the section "Hierarchy levels". Requires a flow built with a hierarchy. |
numeric |
How to summarise numeric variables: |
missing |
When to include the row counting |
digits |
Decimal places for means, SDs, medians, quartiles and
percentages. Default |
drop_randomise |
Logical. Omit |
assessed_label |
Heading for step |
missing_label |
Label of the row counting |
variable_col_label |
Column header for the variable column. Default
|
var_labels |
Optional display names for the variables: a character
vector named by column (e.g. |
A flextable, gt_tbl, or huxtable object.
By default there is one column per step from 0 (the starting data) to
the last step, omitting randomise() steps (see drop_randomise). Column
k holds cohort(flow, step_number = k): the rows that passed steps 1
to k. steps restricts or reorders the columns. Each element is resolved
like at in cohort(): a number is a step number (0 = starting data); a
string is a step label if one matches, else a category, meaning its last
step. Steps named in steps are never dropped, even randomise() steps.
With excluded = TRUE, column k instead holds the rows removed at
step k (those of excluded() with cf_step == k): the usual
supplementary table of excluded participants' characteristics. Step 0
removes nothing and cannot be selected.
A column's heading is the step label, or assessed_label for step 0.
Repeated headings are made unique with " #<n>".
How a variable is summarised depends on its type:
numeric: a "Mean (SD)" row and/or a "Median [IQR]" row (shown
as median [Q1, Q3]), chosen with numeric.
factor: one row per level of the factor, in level order, whether or
not the level occurs; n (%) of the non-missing values.
character: as a factor whose levels are the distinct values in the starting data, sorted.
logical: a single row (level is NA) counting TRUE; n (%) of
the non-missing values.
Each variable also gets a missing_label row counting NA values, as a
percentage of the column's n; missing controls when it appears. Dates
and other types are not summarised: convert them first.
When the flow was built with apply_criteria(hierarchy = ), rows are
summarised unless level names one of the hierarchy's levels, in which
case each unit at that level (each distinct, complete key) contributes
once and n counts units. A row with an NA in the level's key is not a
unit. Every variable must then be constant within each unit across the
starting data; a variable that varies within a unit is an error, since
there is no single value to summarise.
as_characteristics_tibble() for the underlying data layer.
Other reporting:
as_attrition_table(),
as_attrition_tibble(),
as_characteristics_tibble(),
as_consort_diagram(),
as_narrative(),
save_consort_diagram()
dat <- mock_parallel_rct(n_participants = 200, seed = 1) crit <- cf_criteria() |> include(~ age >= 18, label = "Adults only") |> include(~ eligible_screen, label = "Passed screening") |> exclude(~ withdrew, label = "Withdrew consent") flow <- apply_criteria(dat, crit, id = "participant_id") if (requireNamespace("flextable", quietly = TRUE) && requireNamespace("officer", quietly = TRUE)) { as_characteristics_table(flow, vars = c("age", "sex", "withdrew"), var_labels = c(age = "Age, years", sex = "Sex")) } if (requireNamespace("gt", quietly = TRUE)) { as_characteristics_table(flow, vars = c("age", "sex"), backend = "gt", excluded = TRUE) }dat <- mock_parallel_rct(n_participants = 200, seed = 1) crit <- cf_criteria() |> include(~ age >= 18, label = "Adults only") |> include(~ eligible_screen, label = "Passed screening") |> exclude(~ withdrew, label = "Withdrew consent") flow <- apply_criteria(dat, crit, id = "participant_id") if (requireNamespace("flextable", quietly = TRUE) && requireNamespace("officer", quietly = TRUE)) { as_characteristics_table(flow, vars = c("age", "sex", "withdrew"), var_labels = c(age = "Age, years", sex = "Sex")) } if (requireNamespace("gt", quietly = TRUE)) { as_characteristics_table(flow, vars = c("age", "sex"), backend = "gt", excluded = TRUE) }
Summarises chosen variables (demographics, baseline measures) for the
cohort at each step of a flow: a baseline-characteristics ("Table 1")
table with one column per step, each describing the rows surviving up to
and including that step. as_characteristics_tibble() is the data layer;
as_characteristics_table() renders it; stack_cohorts() gives the
per-step rows themselves for other summary-table packages.
as_characteristics_tibble( flow, vars, steps = NULL, excluded = FALSE, level = NULL, numeric = "mean_sd", missing = c("ifany", "always", "never"), digits = 1L, drop_randomise = TRUE, assessed_label = "Assessed for eligibility", missing_label = "Missing", wide = FALSE )as_characteristics_tibble( flow, vars, steps = NULL, excluded = FALSE, level = NULL, numeric = "mean_sd", missing = c("ifany", "always", "never"), digits = 1L, drop_randomise = TRUE, assessed_label = "Assessed for eligibility", missing_label = "Missing", wide = FALSE )
flow |
A |
vars |
Character vector of column names to summarise. |
steps |
Optional step selectors (a vector or list); see the section
"Steps". |
excluded |
Logical. |
level |
Optional hierarchy level name at which to count units; see the section "Hierarchy levels". Requires a flow built with a hierarchy. |
numeric |
How to summarise numeric variables: |
missing |
When to include the row counting |
digits |
Decimal places for means, SDs, medians, quartiles and
percentages. Default |
drop_randomise |
Logical. Omit |
assessed_label |
Heading for step |
missing_label |
Label of the row counting |
wide |
Logical. |
With wide = FALSE, a tibble with one row per variable, summary
row and step, ordered by variable (in vars order), then summary row,
then step column:
variableColumn name
levelFactor level, "Mean (SD)", "Median [IQR]",
missing_label, or NA for a logical variable's single row
stepStep number (0 = starting data)
labelStep heading
nRows (or units, with level) in that step's column
countRows in the level, or missing; NA for numeric
summaries
pctcount as a percentage of the non-missing values (of n
for the missing row); NA where the denominator is zero
statDisplay text: "12 (6.0%)", "45.2 (14.8)",
"45.0 [35.0, 56.0]"; NA when there is nothing to summarise
With wide = TRUE, variable and level followed by one character column
per step, named "<heading> (n = <n>)", holding stat.
By default there is one column per step from 0 (the starting data) to
the last step, omitting randomise() steps (see drop_randomise). Column
k holds cohort(flow, step_number = k): the rows that passed steps 1
to k. steps restricts or reorders the columns. Each element is resolved
like at in cohort(): a number is a step number (0 = starting data); a
string is a step label if one matches, else a category, meaning its last
step. Steps named in steps are never dropped, even randomise() steps.
With excluded = TRUE, column k instead holds the rows removed at
step k (those of excluded() with cf_step == k): the usual
supplementary table of excluded participants' characteristics. Step 0
removes nothing and cannot be selected.
A column's heading is the step label, or assessed_label for step 0.
Repeated headings are made unique with " #<n>".
How a variable is summarised depends on its type:
numeric: a "Mean (SD)" row and/or a "Median [IQR]" row (shown
as median [Q1, Q3]), chosen with numeric.
factor: one row per level of the factor, in level order, whether or
not the level occurs; n (%) of the non-missing values.
character: as a factor whose levels are the distinct values in the starting data, sorted.
logical: a single row (level is NA) counting TRUE; n (%) of
the non-missing values.
Each variable also gets a missing_label row counting NA values, as a
percentage of the column's n; missing controls when it appears. Dates
and other types are not summarised: convert them first.
When the flow was built with apply_criteria(hierarchy = ), rows are
summarised unless level names one of the hierarchy's levels, in which
case each unit at that level (each distinct, complete key) contributes
once and n counts units. A row with an NA in the level's key is not a
unit. Every variable must then be constant within each unit across the
starting data; a variable that varies within a unit is an error, since
there is no single value to summarise.
as_characteristics_table() for a formatted table,
stack_cohorts() for the per-step rows, as_attrition_tibble() for
the attrition counts themselves.
Other reporting:
as_attrition_table(),
as_attrition_tibble(),
as_characteristics_table(),
as_consort_diagram(),
as_narrative(),
save_consort_diagram()
dat <- mock_parallel_rct(n_participants = 200, seed = 1) crit <- cf_criteria() |> include(~ age >= 18, label = "Adults only") |> include(~ eligible_screen, label = "Passed screening") |> exclude(~ withdrew, label = "Withdrew consent") flow <- apply_criteria(dat, crit, id = "participant_id") as_characteristics_tibble(flow, vars = c("age", "sex")) as_characteristics_tibble(flow, vars = c("age", "sex"), wide = TRUE) # Who was removed at each step? as_characteristics_tibble(flow, vars = "age", excluded = TRUE, wide = TRUE) # Only the starting data and the final cohort, with both numeric summaries as_characteristics_tibble(flow, vars = "age", steps = c(0, 3), numeric = c("mean_sd", "median_iqr"), wide = TRUE)dat <- mock_parallel_rct(n_participants = 200, seed = 1) crit <- cf_criteria() |> include(~ age >= 18, label = "Adults only") |> include(~ eligible_screen, label = "Passed screening") |> exclude(~ withdrew, label = "Withdrew consent") flow <- apply_criteria(dat, crit, id = "participant_id") as_characteristics_tibble(flow, vars = c("age", "sex")) as_characteristics_tibble(flow, vars = c("age", "sex"), wide = TRUE) # Who was removed at each step? as_characteristics_tibble(flow, vars = "age", excluded = TRUE, wide = TRUE) # Only the starting data and the final cohort, with both numeric summaries as_characteristics_tibble(flow, vars = "age", steps = c(0, 3), numeric = c("mean_sd", "median_iqr"), wide = TRUE)
Produces a CONSORT-style flow diagram (as used in clinical trial and
cohort study reporting) summarising participant flow through a cf_flow
pipeline. The main vertical flow shows the number of participants
entering the study and surviving each step (or category, when
show_categories = TRUE), while exclusions at each step branch off to
the side as a box giving the count, percentage, and (for categorised
steps) the individual exclusion reasons.
as_consort_diagram( flow, show_categories = TRUE, assessed_label = "Assessed for eligibility", final_label = "Final cohort", digits = 1L, main_fill = NA, excl_fill = NA, border_colour = "black", border_linewidth = 0.5, text_size = 9, text_colour = "#222222", font_family = "", arrow_size = 0.06, title = NULL, title_colour = text_colour, wrap_width = NULL, big_mark = ",", branch_by = NULL, stage_by = NULL, stage_label_by = NULL, count_by = NULL, branch_na_label = "Missing", remaining_label = "Remaining" )as_consort_diagram( flow, show_categories = TRUE, assessed_label = "Assessed for eligibility", final_label = "Final cohort", digits = 1L, main_fill = NA, excl_fill = NA, border_colour = "black", border_linewidth = 0.5, text_size = 9, text_colour = "#222222", font_family = "", arrow_size = 0.06, title = NULL, title_colour = text_colour, wrap_width = NULL, big_mark = ",", branch_by = NULL, stage_by = NULL, stage_label_by = NULL, count_by = NULL, branch_na_label = "Missing", remaining_label = "Remaining" )
flow |
A |
show_categories |
Logical. When |
assessed_label |
Character string for the header row. Default
|
final_label |
Character string for the trailing final-cohort row.
Default |
digits |
Integer. Number of decimal places for |
main_fill |
Fill colour for main-flow boxes. Default |
excl_fill |
Fill colour for exclusion (side) boxes. Default |
border_colour |
Border colour for all boxes and arrows. Default
|
border_linewidth |
Line width for all box borders and arrows,
passed on to |
text_size |
Font size (points) for box text. Default |
text_colour |
Colour for all box text (and the title, unless
|
font_family |
Font family for all box text and the title. Default
|
arrow_size |
Length (in inches) of arrowheads on connector lines,
passed to |
title |
Optional plot title drawn above the diagram. Default |
title_colour |
Colour for the title text. Default |
wrap_width |
Optional integer. Maximum character width for wrapping
text in boxes. When |
big_mark |
Character string used as the thousands-separator when
formatting counts in box labels (e.g. |
branch_by |
Optional column name (string) for allocation branching.
When |
stage_by |
Optional column name (string) for ordered stages within
each branch (e.g. crossover |
stage_label_by |
Optional column name (string) providing labels for
each stage (e.g. crossover |
count_by |
Optional hierarchy level to count instead of rows: a level
name from the flow's |
branch_na_label |
Character string used to label the branch formed by
|
remaining_label |
Text for the main box below an uncategorised
|
This uses the same underlying data layer as as_attrition_table() –
as_attrition_tibble() – so the row structure (header, category, step,
final) is identical across all three output types.
The returned object is a ggplot2::ggplot() plot (with an additional
consort_diagram class), so it can be drawn with print(), combined
with + and further ggplot2 layers/themes, or written to a PNG, TIFF,
PDF, SVG or EPS file sized to fit its layout with
save_consort_diagram().
A consort_diagram object (a ggplot2 ggplot), drawable via
print(). The underlying box/arrow layout data frames are available
via attr(x, "consort_layout") for introspection or custom rendering.
Each main box shows the number remaining after its step, and each exclusion box the number removed, each beside text describing those rows:
An uncategorised include()-type step keeps its label on the main box
("Aged 18 or over (n=194)"). Its exclusion box shows the step's
reason if set ("Under 18 (n=6)"), else "Excluded (n=6)".
An uncategorised exclude()-type step's label goes in the exclusion box
("Withdrew consent (n=4)") and the main box reads remaining_label
("Remaining (n=118)").
A category's main box shows the category name. Its exclusion box lists
each step by reason, falling back to the label; an inclusion step
without a reason reads backwards there, so this case warns (at most
every 8 hours; options(cohortflow.warn_missing_reason = FALSE) turns
the warning off).
as_attrition_tibble() for the underlying plain-tibble data
layer, as_attrition_table() for formatted table output,
save_consort_diagram() to export for manuscript submission.
Other reporting:
as_attrition_table(),
as_attrition_tibble(),
as_characteristics_table(),
as_characteristics_tibble(),
as_narrative(),
save_consort_diagram()
dat <- mock_parallel_rct(n_participants = 200, seed = 1) crit <- cf_criteria() |> include(~ !is.na(age), label = "Age recorded", category = "Valid age", reason = "Age missing") |> include(~ age >= 18, label = "Adults only", category = "Valid age", reason = "Under 18") |> include(~ !is.na(consent_date), label = "Consent recorded", reason = "No consent") |> exclude(~ withdrew, label = "Withdrew consent") flow <- apply_criteria(dat, crit, id = "participant_id") as_consort_diagram(flow)dat <- mock_parallel_rct(n_participants = 200, seed = 1) crit <- cf_criteria() |> include(~ !is.na(age), label = "Age recorded", category = "Valid age", reason = "Age missing") |> include(~ age >= 18, label = "Adults only", category = "Valid age", reason = "Under 18") |> include(~ !is.na(consent_date), label = "Consent recorded", reason = "No consent") |> exclude(~ withdrew, label = "Withdrew consent") flow <- apply_criteria(dat, crit, id = "participant_id") as_consort_diagram(flow)
Writes the attrition cascade as a short paragraph, ready to paste into
the participant-flow part of a methods or results section. The numbers
come from as_attrition_tibble() (and, after a randomise() step, from
the same per-arm re-application as_consort_diagram() uses), so the text
always agrees with the table and the diagram.
as_narrative( flow, assessed_label = "assessed for eligibility", unit = "participants", count_by = NULL, big_mark = ",", digits = 1L, show_categories = TRUE, drop_randomise = FALSE, lowercase_reasons = TRUE, style = c("prose", "bullets") ) ## S3 method for class 'cf_narrative' print(x, ...)as_narrative( flow, assessed_label = "assessed for eligibility", unit = "participants", count_by = NULL, big_mark = ",", digits = 1L, show_categories = TRUE, drop_randomise = FALSE, lowercase_reasons = TRUE, style = c("prose", "bullets") ) ## S3 method for class 'cf_narrative' print(x, ...)
flow |
A |
assessed_label |
Text after the starting count in the first
sentence, as in "Of 200 participants assessed for eligibility".
Default |
unit |
Plural noun for what is counted, used verbatim (it is not
pluralised or inflected). Default |
count_by |
Optional hierarchy level to count instead of rows, passed
to |
big_mark |
Thousands separator for counts ( |
digits |
Decimal places for percentages. Default |
show_categories |
Logical. When |
drop_randomise |
Logical. When |
lowercase_reasons |
Logical. When |
style |
|
x |
A |
... |
Ignored. |
A single string with class c("cf_narrative", "character").
Printing wraps it to the console width; in an R Markdown or Quarto chunk
it is inserted as text. Use as.character() for the bare string.
One sentence per category (or per step with show_categories = FALSE,
and for uncategorised steps). Category names group reasons into a
sentence but are not themselves narrated. Steps and categories that
removed nobody are left out.
The first sentence opens "Of N
The removal text for each step is its reason. Exclusion steps default
to their label; an inclusion step without a reason reads
not meeting "<label>".
A randomise() step gives "The remaining n were randomised to A (n = a)
and B (n = b)." Arms are in factor-level order (else sorted); a missing
arm value forms an arm called "Missing", as in the diagram. After it,
each sentence gives per-arm counts, with percentages of the number of
that arm entering the step.
The last sentence gives the final cohort and its percentage of those assessed, broken down by arm when there are arms.
count_by changes what is counted but not the noun: set unit to match
(e.g. count_by = "participant_id", unit = "participants" for a
crossover trial with one row per participant-period).
Grouped steps read like any other step; units removed only because their
group was removed (n_consequential) are not narrated separately.
Lists use the serial (Oxford) comma: "a, b, and c". The text is a starting point: read it, and edit it to suit the journal's style.
as_attrition_tibble() and as_consort_diagram(), which report
the same numbers.
Other reporting:
as_attrition_table(),
as_attrition_tibble(),
as_characteristics_table(),
as_characteristics_tibble(),
as_consort_diagram(),
save_consort_diagram()
dat <- mock_parallel_rct(n_participants = 200, seed = 1) crit <- cf_criteria() |> include(~ !is.na(age), label = "Age recorded", reason = "Age missing", category = "Age") |> include(~ age >= 18, label = "Aged 18 or over", reason = "Under 18", category = "Age") |> include(~ !is.na(consent_date), label = "Consented", reason = "Did not consent") |> randomise(by = "participant_id", arms = "arm") |> exclude(~ withdrew, label = "Withdrew consent") flow <- apply_criteria(dat, crit, id = "participant_id") as_narrative(flow) as_narrative(flow, style = "bullets") as_narrative(flow, drop_randomise = TRUE)dat <- mock_parallel_rct(n_participants = 200, seed = 1) crit <- cf_criteria() |> include(~ !is.na(age), label = "Age recorded", reason = "Age missing", category = "Age") |> include(~ age >= 18, label = "Aged 18 or over", reason = "Under 18", category = "Age") |> include(~ !is.na(consent_date), label = "Consented", reason = "Did not consent") |> randomise(by = "participant_id", arms = "arm") |> exclude(~ withdrew, label = "Withdrew consent") flow <- apply_criteria(dat, crit, id = "participant_id") as_narrative(flow) as_narrative(flow, style = "bullets") as_narrative(flow, drop_randomise = TRUE)
cf_criteria() initialises an empty criteria pipeline. Use the pipe
operators include(), exclude(), group_include(), group_exclude(),
and select_within() to add steps.
cf_criteria(...)cf_criteria(...)
... |
Optional |
A cf_criteria object.
Other criteria builders:
cf_criterion(),
check_criteria(),
exclude(),
group_exclude(),
group_include(),
include(),
randomise(),
select_within()
has_consent <- function(d) !is.na(d$consent_date) crit <- cf_criteria() |> include(~ age >= 18, label = "Adults only") |> include(has_consent, label = "Consent recorded", category = "Consent") |> exclude(~ withdrew, label = "Withdrew consent", category = "Consent") |> group_include(by = "cluster_id", ~ n() >= 5, label = "Cluster size >= 5") |> select_within(by = "participant_id", ~ consent_date == min(consent_date, na.rm = TRUE), label = "Index operation") crithas_consent <- function(d) !is.na(d$consent_date) crit <- cf_criteria() |> include(~ age >= 18, label = "Adults only") |> include(has_consent, label = "Consent recorded", category = "Consent") |> exclude(~ withdrew, label = "Withdrew consent", category = "Consent") |> group_include(by = "cluster_id", ~ n() >= 5, label = "Cluster size >= 5") |> select_within(by = "participant_id", ~ consent_date == min(consent_date, na.rm = TRUE), label = "Index operation") crit
A cf_criterion represents one inclusion or exclusion step in a cohort
eligibility pipeline. Five step types are supported (see type). The
predicate is always a
one-sided formula or a function; the interpretation depends on
the step type.
cf_criterion( predicate, label, type = c("include", "exclude", "group_include", "group_exclude", "select_within", "randomise"), by = NULL, category = NULL, arms = NULL, reason = NULL )cf_criterion( predicate, label, type = c("include", "exclude", "group_include", "group_exclude", "select_within", "randomise"), by = NULL, category = NULL, arms = NULL, reason = NULL )
predicate |
A one-sided formula or a function.
Formula predicates are evaluated with a data mask, so the rlang pronouns
work in every step type: |
label |
A short human-readable description of this criterion. |
type |
One of |
by |
For grouped step types ( |
category |
An optional character string grouping this criterion with
others for display purposes (e.g. |
arms |
For |
reason |
An optional short description of the rows this step
removes, used wherever removals are listed: the exclusion boxes of
|
A cf_criterion object (an S3 list).
Other criteria builders:
cf_criteria(),
check_criteria(),
exclude(),
group_exclude(),
group_include(),
include(),
randomise(),
select_within()
# Row-wise inclusion cf_criterion(~ age >= 18, label = "Adults only", type = "include") # Grouped under a category, with the text shown for the rows it removes cf_criterion(~ !is.na(age), label = "Age recorded", type = "include", category = "Valid age", reason = "Age missing") # Group-level inclusion (clusters with >= 5 participants) cf_criterion( ~ n() >= 5, label = "Sufficient cluster size", type = "group_include", by = "cluster_id" ) # Select first operation per patient cf_criterion( ~ consent_date == min(consent_date, na.rm = TRUE), label = "Index operation", type = "select_within", by = "participant_id" ) # Randomisation marker (no predicate; excludes nothing) cf_criterion( predicate = NULL, label = "Randomised", type = "randomise", by = "cluster_id", arms = "arm" )# Row-wise inclusion cf_criterion(~ age >= 18, label = "Adults only", type = "include") # Grouped under a category, with the text shown for the rows it removes cf_criterion(~ !is.na(age), label = "Age recorded", type = "include", category = "Valid age", reason = "Age missing") # Group-level inclusion (clusters with >= 5 participants) cf_criterion( ~ n() >= 5, label = "Sufficient cluster size", type = "group_include", by = "cluster_id" ) # Select first operation per patient cf_criterion( ~ consent_date == min(consent_date, na.rm = TRUE), label = "Index operation", type = "select_within", by = "participant_id" ) # Randomisation marker (no predicate; excludes nothing) cf_criterion( predicate = NULL, label = "Randomised", type = "randomise", by = "cluster_id", arms = "arm" )
Builds a data frame with one row for every combination of the supplied
vectors (a full cross-join), for use as the expected argument to
apply_criteria(). This lets attrition be denominated against the units
that should exist (e.g. every participant who was invited) rather than
only the rows actually present in data – so a participant who never
appears in the raw data is still counted as failing the first step that
requires non-missing data, instead of being silently absent from the
denominator.
cf_expected(..., stringsAsFactors = FALSE)cf_expected(..., stringsAsFactors = FALSE)
... |
Named vectors of values, one per grouping variable, e.g.
|
stringsAsFactors |
Passed to |
A tibble with one row per expected combination and one column per
named argument in ....
Other pipeline:
apply_criteria(),
cf_hierarchy(),
continue_criteria()
cf_expected(participant_id = 1:3, visit = c("baseline", "3mo"))cf_expected(participant_id = 1:3, visit = c("baseline", "3mo"))
A cf_hierarchy describes how observational units are nested within each
other (e.g., participants within clusters within sites). It is an ordered
named list mapping role names to column name(s) in the data.
cf_hierarchy(...)cf_hierarchy(...)
... |
Named arguments mapping role labels to column names, e.g.
|
The order of ... is from the finest (innermost) level to the
coarsest (outermost) level. The first role is conventionally the
individual participant.
A cf_hierarchy object (a named list with additional class
attribute).
Other pipeline:
apply_criteria(),
cf_expected(),
continue_criteria()
# Two-level: participants within clusters cf_hierarchy(participant = "pid", cluster = "cid") # Three-level: participants within clusters within sites cf_hierarchy(participant = "pid", cluster = "cluster_id", site = "site_id") # Composite (multi-column) level: stepped-wedge cluster-period cf_hierarchy(participant = "pid", cluster_period = c("cluster_id", "period"), cluster = "cluster_id")# Two-level: participants within clusters cf_hierarchy(participant = "pid", cluster = "cid") # Three-level: participants within clusters within sites cf_hierarchy(participant = "pid", cluster = "cluster_id", site = "site_id") # Composite (multi-column) level: stepped-wedge cluster-period cf_hierarchy(participant = "pid", cluster_period = c("cluster_id", "period"), cluster = "cluster_id")
A pre-flight check run before any step is evaluated. For every step in
criteria, the variables used by a formula predicate, the by column(s)
and the arms column must exist in data. If any are missing,
check_criteria() aborts with one line per offending step, naming the step
number, its label and the missing column(s), instead of letting evaluation
fail later with object 'x' not found.
check_criteria(criteria, data)check_criteria(criteria, data)
criteria |
A |
data |
A data frame. |
apply_criteria() and continue_criteria() call this automatically
(after the expected / join step, so joined columns count as present).
Call it directly to validate a criteria set against a dataset without
applying it.
NULL, invisibly. Called for its side effect of aborting when a
criterion refers to a column not in data.
Variables in a formula predicate count as present when they are a column of
data, or when they resolve in the formula's environment (e.g. a local
min_age <- 18 used as ~ age >= min_age), matching how predicates are
evaluated. A consequence is that a missing column whose name matches an
object on the search path (e.g. c or t) is not reported, because
evaluation would find that object too. The dplyr helpers n(), n_distinct(), cur_group() and
cur_group_id() and the .data / .env pronouns are always allowed;
.data$x is checked as column x. Function names, pkg::fn references
and the right-hand side of obj$field are not treated as columns.
Function predicates cannot be inspected statically and are skipped (their
by / arms columns are still checked); the error message notes which
steps were skipped.
apply_criteria(), continue_criteria().
Other criteria builders:
cf_criteria(),
cf_criterion(),
exclude(),
group_exclude(),
group_include(),
include(),
randomise(),
select_within()
dat <- mock_parallel_rct(n_participants = 50, seed = 1) crit <- cf_criteria() |> include(~ age >= 18, label = "Adults only") |> include(~ !is.na(consent_date), label = "Consent recorded") check_criteria(crit, dat) # passes silently # A column that is not in the data is reported with its step bad <- crit |> exclude(~ lost_to_follow_up, label = "Lost to follow-up") try(check_criteria(bad, dat))dat <- mock_parallel_rct(n_participants = 50, seed = 1) crit <- cf_criteria() |> include(~ age >= 18, label = "Adults only") |> include(~ !is.na(consent_date), label = "Consent recorded") check_criteria(crit, dat) # passes silently # A column that is not in the data is reported with its step bad <- crit |> exclude(~ lost_to_follow_up, label = "Lost to follow-up") try(check_criteria(bad, dat))
Returns the rows that passed all criteria (or, with a step selector, all
criteria up to a chosen step), with the internal .cf_row_id column
removed.
cohort( flow, flag = FALSE, at = NULL, step_number = NULL, label = NULL, category = NULL )cohort( flow, flag = FALSE, at = NULL, step_number = NULL, label = NULL, category = NULL )
flow |
A |
flag |
Logical. When |
at |
Optional automatic step selector (number, label or category); see the section "Intermediate steps". |
step_number |
Optional whole step number ( |
label |
Optional exact step label. |
category |
Optional category name (last step in that category). |
A tibble.
A selector picks a step and means "up to and including that step". With none given, the last step is used. At most one may be given:
step_number: a whole number k from 0 to the number of steps; 0 is
the starting data.
label: an exact step label. Errors if no step, or several steps, have it.
category: a category name; selects the last step in that category.
at: picks automatically. A number is a step_number; a string is a
label if one matches, else a category. A string that is both a label
and a category is an error: use label or category explicitly.
criteria_status() for each row's result on every criterion.
Other flow accessors:
criteria_status(),
excluded(),
stack_cohorts()
dat <- mock_parallel_rct(n_participants = 200, seed = 1) crit <- cf_criteria() |> include(~ !is.na(age), label = "Age recorded") |> include(~ eligible_screen, label = "Passed screening") |> exclude(~ withdrew, label = "Withdrew consent") flow <- apply_criteria(dat, crit) cohort(flow) # final survivors cohort(flow, at = "Passed screening") # screening cohort (auto-select) cohort(flow, label = "Passed screening") # same, explicit nrow(cohort(flow, step_number = 0)) # the starting data excluded(flow, at = 2) # removed by steps 1-2dat <- mock_parallel_rct(n_participants = 200, seed = 1) crit <- cf_criteria() |> include(~ !is.na(age), label = "Age recorded") |> include(~ eligible_screen, label = "Passed screening") |> exclude(~ withdrew, label = "Withdrew consent") flow <- apply_criteria(dat, crit) cohort(flow) # final survivors cohort(flow, at = "Passed screening") # screening cohort (auto-select) cohort(flow, label = "Passed screening") # same, explicit nrow(cohort(flow, step_number = 0)) # the starting data excluded(flow, at = 2) # removed by steps 1-2
Applies additional criteria steps to the surviving cohort of an existing
cf_flow, optionally joining on new columns first. This lets an
attrition pipeline be built up in stages – e.g. apply screening criteria,
then join newly collected follow-up data and continue with further
criteria – while keeping a single, continuous step numbering and
denominators that correctly reflect the cohort at each stage (rather than
restarting counts from the original data).
continue_criteria(flow, criteria, join = NULL, by = NULL)continue_criteria(flow, criteria, join = NULL, by = NULL)
flow |
A |
criteria |
A |
join |
Optional data frame of new columns to attach before evaluating
|
by |
Column name(s) shared by |
Before any new step is evaluated, check_criteria() verifies that every
step refers only to columns present in flow's data plus join, so a
forgotten join fails up front naming the step and the missing column(s).
A cf_flow object whose criteria and steps are the
concatenation of flow's existing pipeline and criteria, with step
numbers continuing on from flow.
Other pipeline:
apply_criteria(),
cf_expected(),
cf_hierarchy()
dat <- mock_parallel_rct(n_participants = 200, seed = 1) crit <- cf_criteria() |> include(~ eligible_screen, label = "Passed screening") flow <- apply_criteria(dat, crit) more_crit <- cf_criteria() |> include(~ !is.na(consent_date), label = "Consent recorded") flow2 <- continue_criteria(flow, more_crit) flow2dat <- mock_parallel_rct(n_participants = 200, seed = 1) crit <- cf_criteria() |> include(~ eligible_screen, label = "Passed screening") flow <- apply_criteria(dat, crit) more_crit <- cf_criteria() |> include(~ !is.na(consent_date), label = "Consent recorded") flow2 <- continue_criteria(flow, more_crit) flow2
Returns one row per row of the starting data and one logical column per
criterion, recording whether the row passed (TRUE), failed (FALSE), or
has no result (NA) for that criterion. Use it to audit who failed what,
or to plot overlapping exclusion reasons, which the step-by-step cascade
hides. To get the cohort itself, use cohort().
criteria_status( flow, mode = c("cumulative", "independent"), sets = c("pass", "fail"), na = c("keep", "false", "drop"), names = c("label", "step"), drop_randomise = TRUE, keep_data = FALSE, as = c("tibble", "data.table", "matrix") )criteria_status( flow, mode = c("cumulative", "independent"), sets = c("pass", "fail"), na = c("keep", "false", "drop"), names = c("label", "step"), drop_randomise = TRUE, keep_data = FALSE, as = c("tibble", "data.table", "matrix") )
flow |
A |
mode |
|
sets |
|
na |
What to do with |
names |
Criterion column names: |
drop_randomise |
Logical. Omit |
keep_data |
Logical. Include the original data columns between the id
column(s) and the criterion columns (default |
as |
Return type: |
For "tibble" and "data.table": the id column(s) given as id
to apply_criteria() (or .cf_row_id if none was given), then the data
columns if keep_data = TRUE, then one logical column per criterion in
step order. Rows are in the original data order. For "matrix": a
logical matrix.
| Value | mode = "cumulative" |
mode = "independent" |
TRUE |
Reached the step and passed it | The criterion holds for the row |
FALSE |
Removed at this step | The criterion fails for the row |
NA |
Not assessed: removed at an earlier step | The predicate gave NA, or a grouped step's by is NA
|
Cumulative mirrors the cascade used by cohort(), excluded() and the
CONSORT diagram, and is built from the recorded steps without re-evaluating
anything. Each row has at most one FALSE. NA means the row never
reached that criterion, which is not the same as failing it; it only
becomes FALSE if you ask for that with na = "false". Missing predicate
values follow the cascade: an include() that evaluates to NA removes
the row (FALSE), an exclude() that evaluates to NA keeps it (TRUE).
Independent evaluates every criterion against the full starting data, ignoring earlier steps, so a row can fail several criteria. Bear in mind:
group_include(), group_exclude() and select_within() depend on
which rows are in each group. Evaluated on the full data, a group can
pass or fail differently than it did in the cascade, where earlier steps
had already removed some of its rows.
In a continue_criteria() flow, columns joined at a later stage are NA
for rows excluded before the join, so later-stage predicates are usually
NA for those rows.
randomise() steps are all TRUE (in cumulative mode they are TRUE
where reached and NA otherwise). They are dropped by default.
Set and overlap plots (e.g. the eulerr, UpSetR or ComplexUpset packages)
take a membership matrix with no missing values. The usual question is how
exclusion reasons overlap, so ask for failures and decide what NA
means:
m <- criteria_status(flow, mode = "independent", sets = "fail",
na = "false", as = "matrix")
# eulerr::euler(m); UpSetR::upset(as.data.frame(m * 1))
cohort() for the cohort itself, excluded() for removed rows.
Other flow accessors:
cohort(),
excluded(),
stack_cohorts()
dat <- mock_parallel_rct(n_participants = 200, seed = 1) crit <- cf_criteria() |> include(~ age >= 18, label = "Adults only") |> include(~ eligible_screen, label = "Passed screening") |> exclude(~ withdrew, label = "Withdrew consent") flow <- apply_criteria(dat, crit, id = "participant_id") criteria_status(flow) # How often each exclusion reason applies, counting overlaps m <- criteria_status(flow, mode = "independent", sets = "fail", na = "false", as = "matrix") colSums(m)dat <- mock_parallel_rct(n_participants = 200, seed = 1) crit <- cf_criteria() |> include(~ age >= 18, label = "Adults only") |> include(~ eligible_screen, label = "Passed screening") |> exclude(~ withdrew, label = "Withdrew consent") flow <- apply_criteria(dat, crit, id = "participant_id") criteria_status(flow) # How often each exclusion reason applies, counting overlaps m <- criteria_status(flow, mode = "independent", sets = "fail", na = "false", as = "matrix") colSums(m)
Add an exclusion criterion to a criteria pipeline
exclude(criteria, predicate, label, category = NULL, reason = NULL)exclude(criteria, predicate, label, category = NULL, reason = NULL)
criteria |
A |
predicate |
A one-sided formula or a function evaluated row-wise. |
label |
A short human-readable description of this criterion. |
category |
An optional string grouping this step with others for
display. |
reason |
An optional short description of the rows this step
removes, shown in diagram exclusion boxes. |
The updated cf_criteria object.
A predicate that evaluates to NA for a row is treated differently by the
two step types, and the difference changes denominators:
include() treats NA as failing: the row is removed. Write
include(~ age >= 18) and rows with missing age are excluded here.
exclude() treats NA as not matching: the row is kept. Write
exclude(~ withdrew) and rows with missing withdrew stay in.
To make the intent explicit, handle NA in the predicate itself, e.g.
include(~ !is.na(age) & age >= 18) or exclude(~ is.na(withdrew) | withdrew).
Grouped steps (group_include(), group_exclude(), select_within())
always remove rows whose by value is NA. To see the raw predicate
values, NA included, use criteria_status() with mode = "independent".
A step has up to two pieces of text, and diagrams put each next to the count it describes:
label names the step. For include(), group_include() and
select_within() it describes the rows kept ("Aged 18 or over"),
and an uncategorised step's main box in as_consort_diagram() shows it
with the number remaining. For exclude() and group_exclude() it
describes the rows removed ("Withdrew consent"), so the diagram
shows it in the exclusion box with the number removed, and the main box
below reads "Remaining (n = ...)".
reason describes the rows removed, for exclusion boxes. Exclusion
steps default to their label. For inclusion steps the label would read
backwards in an exclusion box ("Aged 18 or over (n=6)" for six people
under 18), so give a reason ("Under 18"). Without one, an
uncategorised inclusion step's exclusion box just says "Excluded", and
one listed under a category falls back to its label with a warning.
Attrition tables list every step by label, beside a "Removed" column.
Other criteria builders:
cf_criteria(),
cf_criterion(),
check_criteria(),
group_exclude(),
group_include(),
include(),
randomise(),
select_within()
cf_criteria() |> include(~ !is.na(consent_date), label = "Consent recorded", category = "Consent") |> exclude(~ withdrew, label = "Withdrew consent", category = "Consent")cf_criteria() |> include(~ !is.na(consent_date), label = "Consent recorded", category = "Consent") |> exclude(~ withdrew, label = "Withdrew consent", category = "Consent")
Returns a flat tibble of all rows removed at any step (or, with at, up to
and including a chosen step), with additional
columns cf_step (integer), cf_label (character), cf_type (character),
and cf_category (character, NA if the criterion had no category).
Rows are in step order. Set only = TRUE to get just the rows removed at
the selected step itself.
excluded( flow, at = NULL, step_number = NULL, label = NULL, category = NULL, only = FALSE )excluded( flow, at = NULL, step_number = NULL, label = NULL, category = NULL, only = FALSE )
flow |
A |
at |
Optional automatic step selector (number, label or category); see the section "Intermediate steps". |
step_number |
Optional whole step number ( |
label |
Optional exact step label. |
category |
Optional category name (last step in that category). |
only |
Logical. When |
A tibble with original columns plus cf_step, cf_label,
cf_type, cf_category.
A selector picks a step and means "up to and including that step". With none given, the last step is used. At most one may be given:
step_number: a whole number k from 0 to the number of steps; 0 is
the starting data.
label: an exact step label. Errors if no step, or several steps, have it.
category: a category name; selects the last step in that category.
at: picks automatically. A number is a step_number; a string is a
label if one matches, else a category. A string that is both a label
and a category is an error: use label or category explicitly.
Other flow accessors:
cohort(),
criteria_status(),
stack_cohorts()
dat <- mock_parallel_rct(n_participants = 200, seed = 1) crit <- cf_criteria() |> include(~ !is.na(age), label = "Age recorded") |> include(~ eligible_screen, label = "Passed screening") |> exclude(~ withdrew, label = "Withdrew consent") flow <- apply_criteria(dat, crit) excluded(flow) # removed at any step excluded(flow, at = 2) # removed by steps 1-2 excluded(flow, at = 2, only = TRUE) # removed at step 2 only excluded(flow, label = "Withdrew consent", only = TRUE)dat <- mock_parallel_rct(n_participants = 200, seed = 1) crit <- cf_criteria() |> include(~ !is.na(age), label = "Age recorded") |> include(~ eligible_screen, label = "Passed screening") |> exclude(~ withdrew, label = "Withdrew consent") flow <- apply_criteria(dat, crit) excluded(flow) # removed at any step excluded(flow, at = 2) # removed by steps 1-2 excluded(flow, at = 2, only = TRUE) # removed at step 2 only excluded(flow, label = "Withdrew consent", only = TRUE)
Serialises a cf_criteria object to a human-readable YAML file (or string).
The schema is self-describing and can be re-imported with import_criteria().
export_criteria(criteria, path = NULL, fn_refs = list())export_criteria(criteria, path = NULL, fn_refs = list())
criteria |
A |
path |
A file path to write to. If |
fn_refs |
An optional named list mapping function objects to
|
When path = NULL, the YAML text as a character string (returned
visibly, so it prints at the console). Otherwise, invisibly, the
criteria object.
cohortflow_criteria:
version: 1
steps:
- label: "Adults only"
type: include
kind: formula
by: null
expr: "age >= 18"
fn_ref: null
category: null
reason: "Under 18" # only written when set
A file with a higher version than this package reads is refused with an
error.
Formula-based criteria round-trip cleanly. For function predicates
(kind: function), expr holds the full deparsed function source,
including its argument list and any default values (e.g.
"function(d, thr = 18) d$age >= thr"); complex closures may not
round-trip and a warning is issued. Named exported functions can be stored
as "pkg::name" references via fn_refs. Files written by earlier
versions, which stored the function body in expr and the argument names
in a separate fn_args field, can still be imported, with a warning that
default argument values were not stored and the file should be re-saved.
import_criteria() to read the file back.
Other yaml:
import_criteria()
crit <- cf_criteria() |> include(~ age >= 18, label = "Adults only", category = "Age") |> exclude(~ withdrew, label = "Withdrew consent") # As a string cat(export_criteria(crit)) # To a file, then back again path <- tempfile(fileext = ".yml") export_criteria(crit, path = path) import_criteria(path = path) unlink(path)crit <- cf_criteria() |> include(~ age >= 18, label = "Adults only", category = "Age") |> exclude(~ withdrew, label = "Withdrew consent") # As a string cat(export_criteria(crit)) # To a file, then back again path <- tempfile(fileext = ".yml") export_criteria(crit, path = path) import_criteria(path = path) unlink(path)
The predicate is evaluated per group; groups where the predicate returns
TRUE are removed (all their rows dropped).
group_exclude(criteria, by, predicate, label, category = NULL, reason = NULL)group_exclude(criteria, by, predicate, label, category = NULL, reason = NULL)
criteria |
A |
by |
One or more column names (character vector) to group by; supply more than one for composite (multi-column) grouping. |
predicate |
A one-sided formula using summary functions, or a function. |
label |
A short human-readable description of this criterion. |
category |
An optional string grouping this step with others for
display. |
reason |
An optional short description of the rows this step
removes, shown in diagram exclusion boxes. |
The updated cf_criteria object.
Other criteria builders:
cf_criteria(),
cf_criterion(),
check_criteria(),
exclude(),
group_include(),
include(),
randomise(),
select_within()
cf_criteria() |> group_exclude(by = "cluster_id", ~ mean(is.na(age)) > 0.5, label = "Excessive missing age in cluster")cf_criteria() |> group_exclude(by = "cluster_id", ~ mean(is.na(age)) > 0.5, label = "Excessive missing age in cluster")
The predicate is evaluated in a dplyr::summarise() context per group
(when a formula) or receives a grouped data frame (when a function). Groups
where the predicate returns TRUE are kept; all rows in failing groups are
removed.
group_include(criteria, by, predicate, label, category = NULL, reason = NULL)group_include(criteria, by, predicate, label, category = NULL, reason = NULL)
criteria |
A |
by |
One or more column names (character vector) to group by; supply more than one for composite (multi-column) grouping. |
predicate |
A one-sided formula using summary functions ( |
label |
A short human-readable description of this criterion. |
category |
An optional string grouping this step with others for
display. |
reason |
An optional short description of the rows this step
removes, shown in diagram exclusion boxes. |
The updated cf_criteria object.
Other criteria builders:
cf_criteria(),
cf_criterion(),
check_criteria(),
exclude(),
group_exclude(),
include(),
randomise(),
select_within()
cf_criteria() |> group_include(by = "cluster_id", ~ n() >= 5, label = "Cluster size >= 5")cf_criteria() |> group_include(by = "cluster_id", ~ n() >= 5, label = "Cluster size >= 5")
Reads a YAML file (or string) written by export_criteria() and
reconstructs a cf_criteria object.
import_criteria(path = NULL, text = NULL, envir = parent.frame())import_criteria(path = NULL, text = NULL, envir = parent.frame())
path |
A file path to read from. Exactly one of |
text |
A YAML string. Exactly one of |
envir |
The environment in which to evaluate re-parsed expressions. |
A cf_criteria object.
Criteria files contain R code: every formula and function predicate is
parsed and evaluated when the file is imported (and again when the
criteria are applied), and fn_ref entries are looked up and called.
Treat a criteria file like an R script: do not import files from
untrusted sources.
export_criteria() to write a pipeline.
Other yaml:
export_criteria()
yml <- " cohortflow_criteria: version: 1 steps: - label: Adults only type: include kind: formula expr: age >= 18 - label: Withdrew consent type: exclude kind: formula expr: withdrew " crit <- import_criteria(text = yml) crit dat <- mock_parallel_rct(n_participants = 100, seed = 1) apply_criteria(dat, crit)yml <- " cohortflow_criteria: version: 1 steps: - label: Adults only type: include kind: formula expr: age >= 18 - label: Withdrew consent type: exclude kind: formula expr: withdrew " crit <- import_criteria(text = yml) crit dat <- mock_parallel_rct(n_participants = 100, seed = 1) apply_criteria(dat, crit)
Add an inclusion criterion to a criteria pipeline
include(criteria, predicate, label, category = NULL, reason = NULL)include(criteria, predicate, label, category = NULL, reason = NULL)
criteria |
A |
predicate |
A one-sided formula or a function evaluated row-wise. |
label |
A short human-readable description of this criterion. See the Labels section. |
category |
An optional string grouping this step with others for
display (e.g. |
reason |
An optional short description of the rows this step
removes, shown in diagram exclusion boxes. |
The updated cf_criteria object.
A predicate that evaluates to NA for a row is treated differently by the
two step types, and the difference changes denominators:
include() treats NA as failing: the row is removed. Write
include(~ age >= 18) and rows with missing age are excluded here.
exclude() treats NA as not matching: the row is kept. Write
exclude(~ withdrew) and rows with missing withdrew stay in.
To make the intent explicit, handle NA in the predicate itself, e.g.
include(~ !is.na(age) & age >= 18) or exclude(~ is.na(withdrew) | withdrew).
Grouped steps (group_include(), group_exclude(), select_within())
always remove rows whose by value is NA. To see the raw predicate
values, NA included, use criteria_status() with mode = "independent".
A step has up to two pieces of text, and diagrams put each next to the count it describes:
label names the step. For include(), group_include() and
select_within() it describes the rows kept ("Aged 18 or over"),
and an uncategorised step's main box in as_consort_diagram() shows it
with the number remaining. For exclude() and group_exclude() it
describes the rows removed ("Withdrew consent"), so the diagram
shows it in the exclusion box with the number removed, and the main box
below reads "Remaining (n = ...)".
reason describes the rows removed, for exclusion boxes. Exclusion
steps default to their label. For inclusion steps the label would read
backwards in an exclusion box ("Aged 18 or over (n=6)" for six people
under 18), so give a reason ("Under 18"). Without one, an
uncategorised inclusion step's exclusion box just says "Excluded", and
one listed under a category falls back to its label with a warning.
Attrition tables list every step by label, beside a "Removed" column.
Other criteria builders:
cf_criteria(),
cf_criterion(),
check_criteria(),
exclude(),
group_exclude(),
group_include(),
randomise(),
select_within()
cf_criteria() |> include(~ age >= 18, label = "Adults", category = "Valid age", reason = "Under 18")cf_criteria() |> include(~ age >= 18, label = "Adults", category = "Valid age", reason = "Under 18")
Produces one row per participant, nested within clusters (e.g. GP
practices, schools) that are themselves nested within sites. Each
cluster – not each participant – is randomised to an arm, so all
participants within a cluster share the same arm.
mock_cluster_rct( n_clusters = 12L, n_participants = 480L, n_sites = 3L, arm_labels = c("Control", "Intervention"), seed = 123L )mock_cluster_rct( n_clusters = 12L, n_participants = 480L, n_sites = 3L, arm_labels = c("Control", "Intervention"), seed = 123L )
n_clusters |
Integer. Number of clusters. |
n_participants |
Integer. Total number of participants, distributed unevenly across clusters. |
n_sites |
Integer. Number of sites (clusters nested in sites; must
be <= |
arm_labels |
Character vector. Labels for the trial arms; clusters are allocated to these labels with balanced randomisation. |
seed |
Integer. Random seed for reproducibility. |
A tibble::tibble() with one row per participant, including
participant_id, cluster_id, site_id, arm (cluster-level),
demographic columns, and consent-flow columns.
Other mock data:
mock_crossover(),
mock_parallel_rct(),
mock_stepped_wedge()
mock_cluster_rct() mock_cluster_rct(n_clusters = 20, n_participants = 800, seed = 5)mock_cluster_rct() mock_cluster_rct(n_clusters = 20, n_participants = 800, seed = 5)
Deprecated. mock_cohortflow() is deprecated in favour of
design-specific generators that produce realistic data for common study
designs: mock_parallel_rct(), mock_crossover(), mock_cluster_rct(),
and mock_stepped_wedge(). Those functions include an explicit arm
column and design-appropriate structure (e.g. cluster-level
randomisation, within-participant crossover sequences, stepped-wedge
roll-out), which mock_cohortflow() never modelled.
Produces a tibble that mimics a clustered cohort study with optional stepped-wedge period structure. The returned data is deliberately imperfect: some participants have missing values, withdrew consent, or failed screening, so that inclusion/exclusion criteria have something to remove.
mock_cohortflow( n_participants = 500L, n_clusters = 10L, n_sites = 3L, n_periods = 4L, seed = 123L )mock_cohortflow( n_participants = 500L, n_clusters = 10L, n_sites = 3L, n_periods = 4L, seed = 123L )
n_participants |
Integer. Total number of participant rows. |
n_clusters |
Integer. Number of clusters (e.g., GP practices, schools). |
n_sites |
Integer. Number of sites (clusters are nested in sites;
must be <= |
n_periods |
Integer. Number of time periods (e.g., waves in a
stepped-wedge design). Set to |
seed |
Integer. Random seed for reproducibility. |
A tibble::tibble() with columns:
participant_idCharacter. Unique participant identifier.
event_idCharacter. Unique event (row) identifier – useful when the dataset has multiple rows per participant (e.g., one per operation).
cluster_idCharacter. Cluster identifier.
site_idCharacter. Site identifier (clusters nested in sites).
periodInteger. Study period (1 = first period).
sequenceInteger. Stepped-wedge sequence the cluster is assigned
to (NA if n_periods == 1).
ageNumeric. Age in years (some NAs to simulate missing data).
age_groupCharacter. Age group ("<18", "18-39", "40-64", "65+").
sexCharacter. "M" / "F" / "O" (other).
ethnicityCharacter. One of five broad ethnic groups.
consent_dateDate. Date of consent (NA = did not consent).
baseline_completeLogical. Whether the baseline assessment is complete.
withdrewLogical. Whether the participant withdrew after consent.
eligible_screenLogical. Whether the participant passed initial eligibility screening (e.g., diagnosis confirmed).
mock_cohortflow() # Larger study with three periods mock_cohortflow(n_participants = 2000, n_clusters = 20, n_periods = 3, seed = 42)mock_cohortflow() # Larger study with three periods mock_cohortflow(n_participants = 2000, n_clusters = 20, n_periods = 3, seed = 42)
Produces one row per participant per period. Each participant is assigned
a randomisation sequence (e.g. "AB" or "BA" for a two-period,
two-treatment design), and the arm in each period is derived from that
sequence – so participants genuinely switch treatments across periods
rather than arm being an unused label.
mock_crossover(n_participants = 120L, arm_labels = c("A", "B"), seed = 123L)mock_crossover(n_participants = 120L, arm_labels = c("A", "B"), seed = 123L)
n_participants |
Integer. Number of participants. |
arm_labels |
Character vector. Labels for the treatments being
crossed over. Determines both the number of periods
( |
seed |
Integer. Random seed for reproducibility. |
A tibble::tibble() with one row per participant per period,
including participant_id, event_id, period, sequence, arm,
demographic columns, and consent-flow columns. Consent-flow columns
(eligible_screen, consent_date, baseline_complete, withdrew)
are constant within a participant across periods, since they describe
trial-level (not period-level) status; withdrew reflects withdrawal
at any point during the trial.
Other mock data:
mock_cluster_rct(),
mock_parallel_rct(),
mock_stepped_wedge()
mock_crossover() mock_crossover(n_participants = 60, arm_labels = c("Drug", "Placebo"), seed = 3)mock_crossover() mock_crossover(n_participants = 60, arm_labels = c("Drug", "Placebo"), seed = 3)
Produces one row per participant, individually randomised to one of
length(arm_labels) arms with equal allocation. No clustering or
repeated measures – the simplest of the four designs.
mock_parallel_rct( n_participants = 300L, arm_labels = c("Control", "Intervention"), seed = 123L )mock_parallel_rct( n_participants = 300L, arm_labels = c("Control", "Intervention"), seed = 123L )
n_participants |
Integer. Total number of participants. |
arm_labels |
Character vector. Labels for the trial arms (allocation is balanced across these labels). |
seed |
Integer. Random seed for reproducibility. |
A tibble::tibble() with one row per participant, including
participant_id, arm, demographic columns (age, age_group,
sex, ethnicity), and consent-flow columns (eligible_screen,
consent_date, baseline_complete, withdrew).
Other mock data:
mock_cluster_rct(),
mock_crossover(),
mock_stepped_wedge()
mock_parallel_rct() mock_parallel_rct(n_participants = 300, arm_labels = c("Placebo", "Drug"), seed = 7)mock_parallel_rct() mock_parallel_rct(n_participants = 300, arm_labels = c("Placebo", "Drug"), seed = 7)
Produces one row per participant per period, with clusters nested within
sites. Each cluster is assigned a crossover sequence – the period in
which it switches from control to intervention – and every cluster
eventually receives the intervention (the defining feature of a stepped
wedge). The arm for a given participant-period row is derived from
whether the current period has reached the cluster's sequence
(period >= sequence), so treatment assignment is genuinely driven by
the roll-out schedule rather than an unused column.
mock_stepped_wedge( n_clusters = 12L, n_participants = 480L, n_periods = 4L, n_sites = 3L, arm_labels = c("Control", "Intervention"), seed = 123L )mock_stepped_wedge( n_clusters = 12L, n_participants = 480L, n_periods = 4L, n_sites = 3L, arm_labels = c("Control", "Intervention"), seed = 123L )
n_clusters |
Integer. Number of clusters. |
n_participants |
Integer. Total number of participants (each contributes one row per period), distributed unevenly across clusters. |
n_periods |
Integer. Number of periods, including the initial all-control period. Must be >= 2 (clusters need at least one period before crossover and one after). |
n_sites |
Integer. Number of sites (clusters nested in sites; must
be <= |
arm_labels |
Character vector of length 2: |
seed |
Integer. Random seed for reproducibility. |
A tibble::tibble() with one row per participant per period,
including participant_id, event_id, cluster_id, site_id,
period, sequence, arm (derived from period >= sequence),
demographic columns, and consent-flow columns.
Other mock data:
mock_cluster_rct(),
mock_crossover(),
mock_parallel_rct()
mock_stepped_wedge() mock_stepped_wedge(n_clusters = 8, n_participants = 400, n_periods = 5, seed = 9)mock_stepped_wedge() mock_stepped_wedge(n_clusters = 8, n_participants = 400, n_periods = 5, seed = 9)
cf_flow objectsA thin wrapper around as_consort_diagram() so that plot(flow) draws a
CONSORT flow diagram directly from a cf_flow object.
## S3 method for class 'cf_flow' plot(x, ...)## S3 method for class 'cf_flow' plot(x, ...)
x |
A |
... |
Additional arguments passed on to |
A consort_diagram object, invisibly printed.
dat <- mock_parallel_rct(n_participants = 100, seed = 1) crit <- cf_criteria() |> include(~ age >= 18, label = "Adults only") |> exclude(~ withdrew, label = "Withdrew consent") flow <- apply_criteria(dat, crit) plot(flow) plot(flow, wrap_width = 20, title = "Participant flow")dat <- mock_parallel_rct(n_participants = 100, seed = 1) crit <- cf_criteria() |> include(~ age >= 18, label = "Adults only") |> exclude(~ withdrew, label = "Withdrew consent") flow <- apply_criteria(dat, crit) plot(flow) plot(flow, wrap_width = 20, title = "Participant flow")
consort_diagram objectsDraws a consort_diagram (produced by as_consort_diagram()) on the
current graphics device via the standard ggplot2 print method (which
opens a new page before drawing).
## S3 method for class 'consort_diagram' print(x, ...)## S3 method for class 'consort_diagram' print(x, ...)
x |
A |
... |
Additional arguments passed on to |
x, invisibly.
dat <- mock_parallel_rct(n_participants = 100, seed = 1) crit <- cf_criteria() |> include(~ age >= 18, label = "Adults only") diagram <- as_consort_diagram(apply_criteria(dat, crit)) print(diagram)dat <- mock_parallel_rct(n_participants = 100, seed = 1) crit <- cf_criteria() |> include(~ age >= 18, label = "Adults only") diagram <- as_consort_diagram(apply_criteria(dat, crit)) print(diagram)
randomise() records where allocation happens in the pipeline without
excluding any rows (n_fail is always 0). as_consort_diagram() and
as_attrition_tibble() use its by/arms to default branch_by when
not explicitly supplied, and steps at or after it are flagged
post_randomisation in as_attrition_tibble()'s output.
randomise(criteria, by, arms, label = "Randomised", category = NULL)randomise(criteria, by, arms, label = "Randomised", category = NULL)
criteria |
A |
by |
One or more column names (character vector) naming the
randomisation unit (e.g. |
arms |
A single column name (string) holding each unit's allocated
arm (e.g. |
label |
A short human-readable description of this step. Default
|
category |
An optional string grouping this step with others for
display. |
The updated cf_criteria object.
Other criteria builders:
cf_criteria(),
cf_criterion(),
check_criteria(),
exclude(),
group_exclude(),
group_include(),
include(),
select_within()
cf_criteria() |> include(~ eligible, label = "Eligible clusters") |> randomise(by = "cluster_id", arms = "arm") |> exclude(~ withdrew, label = "Withdrew after allocation")cf_criteria() |> include(~ eligible, label = "Eligible clusters") |> randomise(by = "cluster_id", arms = "arm") |> exclude(~ withdrew, label = "Withdrew after allocation")
Writes a CONSORT flow diagram to a PNG, TIFF, JPEG, PDF, SVG or EPS file
via ggplot2::ggsave(), with defaults suited to journal submission:
300 dpi raster output, a white background, and a page size derived from
the diagram's layout so that box text fits its boxes.
save_consort_diagram( diagram, path, width = NULL, height = NULL, units = c("in", "cm", "mm", "px"), dpi = 300, ... )save_consort_diagram( diagram, path, width = NULL, height = NULL, units = c("in", "cm", "mm", "px"), dpi = 300, ... )
diagram |
A |
path |
File to write. The extension ( |
width, height
|
Plot size in |
units |
Units of |
dpi |
Resolution for raster formats. Default |
... |
Further arguments passed to |
The file format is chosen from the extension of path. PNG, TIFF and
JPEG use the ragg devices when that package is installed (sharper,
anti-aliased text), otherwise the base grDevices::png() family. PDF uses
grDevices::cairo_pdf() when R has cairo support, which embeds fonts (so
a custom font_family renders correctly), otherwise grDevices::pdf().
SVG uses svglite::svglite() when installed, otherwise
grDevices::svg().
When width and height are both NULL, the size is taken from the
diagram's layout so that text_size-point text fills its boxes, scaled
up proportionally for larger text_size. A longer pipeline therefore
produces a taller file. Supply only one of width / height to fix it
and keep the diagram's aspect ratio. Text is always drawn at
text_size points, so a size much smaller than the natural one will
overflow the boxes and a much larger one leaves them sparse. To fit a
wide diagram (e.g. a two-arm trial) on the page, build it with a smaller
text_size in as_consort_diagram(); the natural size shrinks in
proportion.
path, invisibly.
Other reporting:
as_attrition_table(),
as_attrition_tibble(),
as_characteristics_table(),
as_characteristics_tibble(),
as_consort_diagram(),
as_narrative()
dat <- mock_parallel_rct(n_participants = 200, seed = 1) crit <- cf_criteria() |> include(~ !is.na(age), label = "Age recorded") |> include(~ age >= 18, label = "Adults only") |> exclude(~ withdrew, label = "Withdrew consent") flow <- apply_criteria(dat, crit) png_file <- tempfile(fileext = ".png") save_consort_diagram(flow, png_file) pdf_file <- tempfile(fileext = ".pdf") diagram <- as_consort_diagram(flow, title = "Participant flow") save_consort_diagram(diagram, pdf_file, width = 6) unlink(c(png_file, pdf_file))dat <- mock_parallel_rct(n_participants = 200, seed = 1) crit <- cf_criteria() |> include(~ !is.na(age), label = "Age recorded") |> include(~ age >= 18, label = "Adults only") |> exclude(~ withdrew, label = "Withdrew consent") flow <- apply_criteria(dat, crit) png_file <- tempfile(fileext = ".png") save_consort_diagram(flow, png_file) pdf_file <- tempfile(fileext = ".pdf") diagram <- as_consort_diagram(flow, title = "Participant flow") save_consort_diagram(diagram, pdf_file, width = 6) unlink(c(png_file, pdf_file))
The predicate is evaluated separately within each group defined by by and
must return a logical vector the same length as the group. Rows where the
predicate is FALSE are dropped and recorded in the excluded rows store.
This is the natural way to select one (or more) records per unit, e.g. the
index operation per patient.
select_within(criteria, by, predicate, label, category = NULL, reason = NULL)select_within(criteria, by, predicate, label, category = NULL, reason = NULL)
criteria |
A |
by |
One or more column names (character vector) defining the
grouping (e.g. |
predicate |
A one-sided formula evaluated within each group, or a function that receives a group's rows as a data frame and returns a logical vector. |
label |
A short human-readable description of this step. |
category |
An optional string grouping this step with others for
display. |
reason |
An optional short description of the rows this step
removes, shown in diagram exclusion boxes. |
The updated cf_criteria object.
Other criteria builders:
cf_criteria(),
cf_criterion(),
check_criteria(),
exclude(),
group_exclude(),
group_include(),
include(),
randomise()
cf_criteria() |> select_within(by = "participant_id", ~ consent_date == min(consent_date, na.rm = TRUE), label = "Index operation per patient")cf_criteria() |> select_within(by = "participant_id", ~ consent_date == min(consent_date, na.rm = TRUE), label = "Index operation per patient")
Returns the rows of the cohort surviving each step (or, with
excluded = TRUE, the rows removed at each step), stacked with a step
factor and a step_number column in front of the original columns. A row
that survives several steps appears once per step. This is the input shape
summary-table packages expect, e.g.
gtsummary::tbl_summary(stack_cohorts(flow), by = step, include = c(age, sex));
as_characteristics_tibble() is the dependency-light equivalent.
stack_cohorts( flow, steps = NULL, excluded = FALSE, level = NULL, drop_randomise = TRUE, assessed_label = "Assessed for eligibility" )stack_cohorts( flow, steps = NULL, excluded = FALSE, level = NULL, drop_randomise = TRUE, assessed_label = "Assessed for eligibility" )
flow |
A |
steps |
Optional step selectors (a vector or list); see the section
"Steps". |
excluded |
Logical. |
level |
Optional hierarchy level name at which to count units; see the section "Hierarchy levels". Requires a flow built with a hierarchy. |
drop_randomise |
Logical. Omit |
assessed_label |
Heading for step |
A tibble: step_number (integer), step (factor whose levels are
the step headings in column order), then the data columns. With level,
only the level's key column(s) and the columns constant within every
unit of that level are kept.
By default there is one column per step from 0 (the starting data) to
the last step, omitting randomise() steps (see drop_randomise). Column
k holds cohort(flow, step_number = k): the rows that passed steps 1
to k. steps restricts or reorders the columns. Each element is resolved
like at in cohort(): a number is a step number (0 = starting data); a
string is a step label if one matches, else a category, meaning its last
step. Steps named in steps are never dropped, even randomise() steps.
With excluded = TRUE, column k instead holds the rows removed at
step k (those of excluded() with cf_step == k): the usual
supplementary table of excluded participants' characteristics. Step 0
removes nothing and cannot be selected.
A column's heading is the step label, or assessed_label for step 0.
Repeated headings are made unique with " #<n>".
When the flow was built with apply_criteria(hierarchy = ), rows are
summarised unless level names one of the hierarchy's levels, in which
case each unit at that level (each distinct, complete key) contributes
once and n counts units. A row with an NA in the level's key is not a
unit. Every variable must then be constant within each unit across the
starting data; a variable that varies within a unit is an error, since
there is no single value to summarise.
as_characteristics_tibble(), cohort(), excluded().
Other flow accessors:
cohort(),
criteria_status(),
excluded()
dat <- mock_parallel_rct(n_participants = 200, seed = 1) crit <- cf_criteria() |> include(~ age >= 18, label = "Adults only") |> include(~ eligible_screen, label = "Passed screening") |> exclude(~ withdrew, label = "Withdrew consent") flow <- apply_criteria(dat, crit, id = "participant_id") stacked <- stack_cohorts(flow) table(stacked$step)dat <- mock_parallel_rct(n_participants = 200, seed = 1) crit <- cf_criteria() |> include(~ age >= 18, label = "Adults only") |> include(~ eligible_screen, label = "Passed screening") |> exclude(~ withdrew, label = "Withdrew consent") flow <- apply_criteria(dat, crit, id = "participant_id") stacked <- stack_cohorts(flow) table(stacked$step)