Package 'cohortflow'

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

Help Index


Apply a criteria pipeline to a data frame

Description

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.

Usage

apply_criteria(
  data,
  criteria,
  id = NULL,
  expected = NULL,
  by = NULL,
  hierarchy = NULL
)

Arguments

data

A data frame.

criteria

A cf_criteria object.

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 NULL (default), the function looks for .cf_row_id in data; if not found, a sequential integer is added.

expected

Optional data frame (typically built with cf_expected()) listing every observational unit that is expected to exist, e.g. one row per participant. When supplied, data is right-joined onto expected (by by) before any steps are evaluated, so units with no matching row in data are added as all-NA (except for the by column(s)) and are counted correctly as failing the first step that requires non-missing data. Requires by.

by

Column name(s) shared by data and expected used to join them. Required, and only used, when expected is supplied.

hierarchy

Optional cf_hierarchy describing how rows nest into coarser units (e.g. participants within clusters). When supplied, every hierarchy column is validated against data, and each step record additionally stores the number of distinct units at risk/passing/failing at every level (see as_attrition_tibble()'s levels argument).

Details

Before any step is evaluated, check_criteria() verifies that every step refers only to columns present in data (after any expected join).

Value

A cf_flow object.

Row identity

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.

Step types

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).

See Also

Other pipeline: cf_expected(), cf_hierarchy(), continue_criteria()

Examples

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)

Format an attrition table from a cohort flow object

Description

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_flow object produced by apply_criteria().

backend

Character string: "flextable" (default), "gt", or "huxtable".

show_categories

Logical. When TRUE (default) steps with the same category are collapsed under a single parent row. When FALSE one 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. Default 1. 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 levels is supplied and show_consequential resolves to TRUE. Default "Consequential".

branch_by

Optional column name (string) for allocation branching. When NULL (default), the table has a single n column unless the pipeline has a randomise() step, in which case its arms column 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. Use final_label = "Randomised" when appropriate. Cannot be combined with group_x/group_y. Rows whose branch value is NA form their own branch, labelled branch_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_removed and 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. Requires apply_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.9016 count_by took any column and changed only the branch columns, leaving n counting rows.)

branch_na_label

Character string used to label the branch formed by NA values in branch_by (and, in as_consort_diagram(), the stage formed by NA values in stage_by). Default "Missing". Ignored when the column has no NA values.

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_x column headings (e.g. "Site" to show "Site: A"). Default NULL (show the group value alone).

group_y_label

Optional prefix label for group_y row headings (e.g. "Period" to show "Period: 1"). Default NULL (show the group value alone).

group_na_label

Character string used to label the group formed by NA values in group_x/group_y (see the Grouping section). Default "Missing". Ignored when the corresponding grouping column has no NA values.

levels

Optional; requires flow to have been built with apply_criteria(hierarchy = ...). When the default character(0), this argument is ignored and the row-count behaviour above is unchanged. When NULL, one stacked block per hierarchy level is returned (finest to coarsest), each with a level column and an additional n_consequential column (see apply_criteria()'s hierarchy argument for the counting rule). When a character vector of level name(s), only those levels are returned, in the order given. Cannot be combined with group_x/group_y, branch_by, or count_by. A row with an NA in 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 with levels, or a vector named by level (e.g. c(trial = "Trials", participant = "Participants")). Default NULL, 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; supply level_labels to get "Trials" from a level named trial. Ignored unless levels is supplied.

show_consequential

Logical, or NULL (default). Controls whether an extra "consequential" column is shown per level, reporting units lost only because a group_include()/group_exclude() group they belonged to was removed (see levels on as_attrition_tibble()). When NULL, 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 unless levels is 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. Default NULL (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. Default c("#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) 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.

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_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.

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

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)

Build an attrition tibble from a cohort flow object

Description

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.

Usage

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"
)

Arguments

flow

A cf_flow object produced by apply_criteria().

show_categories

Logical. When TRUE (default) steps with the same category are collapsed under a single parent row. When FALSE one 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. Default 1. Formatted tables and diagrams keep trailing zeros ("10.0%").

branch_by

Optional column name (string) for allocation branching. When NULL (default), the table has a single n column unless the pipeline has a randomise() step, in which case its arms column 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. Use final_label = "Randomised" when appropriate. Cannot be combined with group_x/group_y. Rows whose branch value is NA form their own branch, labelled branch_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_removed and 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. Requires apply_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.9016 count_by took any column and changed only the branch columns, leaving n counting rows.)

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_na_label

Character string used to label the group formed by NA values in group_x/group_y (see the Grouping section). Default "Missing". Ignored when the corresponding grouping column has no NA values.

levels

Optional; requires flow to have been built with apply_criteria(hierarchy = ...). When the default character(0), this argument is ignored and the row-count behaviour above is unchanged. When NULL, one stacked block per hierarchy level is returned (finest to coarsest), each with a level column and an additional n_consequential column (see apply_criteria()'s hierarchy argument for the counting rule). When a character vector of level name(s), only those levels are returned, in the order given. Cannot be combined with group_x/group_y, branch_by, or count_by. A row with an NA in 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.

branch_na_label

Character string used to label the branch formed by NA values in branch_by (and, in as_consort_diagram(), the stage formed by NA values in stage_by). Default "Missing". Ignored when the column has no NA values.

Value

A tibble::tibble() with columns:

row_type

"header", "category", "step", or "final"

label

Display text for the row

indent_level

0 = header/final, 1 = category or top-level step, 2 = sub-step under a category

n

Number of participants at this point (N entering for category/step rows; N surviving for the final row)

n_removed

Number removed at this step (NA for header/final)

pct_removed

Percentage 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.

Row structure

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.

Percentage columns

  • 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.

Grouping (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.

See Also

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()

Examples

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)

Render a step-wise characteristics table

Description

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.

Usage

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
)

Arguments

flow

A cf_flow object produced by apply_criteria().

vars

Character vector of column names to summarise.

backend

Character string: "flextable" (default), "gt", or "huxtable".

steps

Optional step selectors (a vector or list); see the section "Steps". NULL (default) means every step.

excluded

Logical. FALSE (default) describes the cohort surviving each step; TRUE describes the rows removed at each step.

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: "mean_sd" (default), "median_iqr", or both.

missing

When to include the row counting NA values per variable: "ifany" (default) if any column has one, "always", or "never".

digits

Decimal places for means, SDs, medians, quartiles and percentages. Default 1.

drop_randomise

Logical. Omit randomise() steps when steps is NULL (default TRUE).

assessed_label

Heading for step 0, the starting data. Default "Assessed for eligibility".

missing_label

Label of the row counting NA values. Default "Missing".

variable_col_label

Column header for the variable column. Default "Characteristic".

var_labels

Optional display names for the variables: a character vector named by column (e.g. c(age = "Age, years")), or an unnamed vector aligned with vars. Unlisted variables show their column name.

Value

A flextable, gt_tbl, or huxtable object.

Steps

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>".

Summaries

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.

Hierarchy levels

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.

See Also

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()

Examples

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)
}

Characteristics of the cohort at each step

Description

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.

Usage

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
)

Arguments

flow

A cf_flow object produced by apply_criteria().

vars

Character vector of column names to summarise.

steps

Optional step selectors (a vector or list); see the section "Steps". NULL (default) means every step.

excluded

Logical. FALSE (default) describes the cohort surviving each step; TRUE describes the rows removed at each step.

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: "mean_sd" (default), "median_iqr", or both.

missing

When to include the row counting NA values per variable: "ifany" (default) if any column has one, "always", or "never".

digits

Decimal places for means, SDs, medians, quartiles and percentages. Default 1.

drop_randomise

Logical. Omit randomise() steps when steps is NULL (default TRUE).

assessed_label

Heading for step 0, the starting data. Default "Assessed for eligibility".

missing_label

Label of the row counting NA values. Default "Missing".

wide

Logical. FALSE (default) returns the long form; TRUE pivots the columns to one per step for display.

Value

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:

variable

Column name

level

Factor level, "Mean (SD)", "Median [IQR]", missing_label, or NA for a logical variable's single row

step

Step number (0 = starting data)

label

Step heading

n

Rows (or units, with level) in that step's column

count

Rows in the level, or missing; NA for numeric summaries

pct

count as a percentage of the non-missing values (of n for the missing row); NA where the denominator is zero

stat

Display 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.

Steps

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>".

Summaries

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.

Hierarchy levels

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.

See Also

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()

Examples

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)

Build a CONSORT flow diagram from a cohort flow object

Description

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.

Usage

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"
)

Arguments

flow

A cf_flow object produced by apply_criteria().

show_categories

Logical. When TRUE (default) steps with the same category are collapsed under a single parent row. When FALSE one 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. Default 1. Formatted tables and diagrams keep trailing zeros ("10.0%").

main_fill

Fill colour for main-flow boxes. Default NA (no fill / transparent), keeping the diagram colourless unless a fill is explicitly supplied.

excl_fill

Fill colour for exclusion (side) boxes. Default NA (no fill / transparent).

border_colour

Border colour for all boxes and arrows. Default "#000000" (black).

border_linewidth

Line width for all box borders and arrows, passed on to ggplot2::geom_rect() / ggplot2::geom_segment(). Default 0.5 (the ggplot2 default line width).

text_size

Font size (points) for box text. Default 9.

text_colour

Colour for all box text (and the title, unless title_colour is supplied). Default "#222222".

font_family

Font family for all box text and the title. Default "" (the device's default font family).

arrow_size

Length (in inches) of arrowheads on connector lines, passed to grid::arrow(). Default 0.06 (smaller than the historical default of 0.1, which looked oversized relative to typical box sizes).

title

Optional plot title drawn above the diagram. Default NULL (no title).

title_colour

Colour for the title text. Default text_colour.

wrap_width

Optional integer. Maximum character width for wrapping text in boxes. When NULL (default), text is not wrapped. When a positive integer, each line in a box label is wrapped to at most that many characters using word-boundary wrapping.

big_mark

Character string used as the thousands-separator when formatting counts in box labels (e.g. "1,234" with the default ","). Pass "" to disable grouping (e.g. "1234").

branch_by

Optional column name (string) for allocation branching. When NULL (default), the diagram is linear unless the pipeline has a randomise() step, in which case its arms column is used automatically. When the pipeline has a randomise() step, the diagram is drawn as one shared trunk up to and including the randomisation box, which then splits (via a right-angle "elbow" connector) into one independent column of main boxes per arm for every step at or after randomisation – so post-allocation exclusions are shown as per-arm sub-cascades rather than shared-trunk boxes. When there is no randomise() step, the surviving cohort is instead split by this column and a single box per branch is drawn below the final common-flow box (the historical behaviour), connected the same way. Use final_label = "Randomised" when appropriate.

stage_by

Optional column name (string) for ordered stages within each branch (e.g. crossover period). When NULL (default), no stage-specific nodes are drawn.

stage_label_by

Optional column name (string) providing labels for each stage (e.g. crossover arm). Ignored when stage_by is NULL.

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 box, trunk, arms and stages, then counts distinct units, so a crossover trial reports participants rather than participant-periods throughout. Requires apply_criteria(hierarchy = ); see as_attrition_tibble().

branch_na_label

Character string used to label the branch formed by NA values in branch_by (and, in as_consort_diagram(), the stage formed by NA values in stage_by). Default "Missing". Ignored when the column has no NA values.

remaining_label

Text for the main box below an uncategorised exclude() or group_exclude() step. That step's label describes the rows it removed, so it appears in the exclusion box beside the number removed, and the main box shows this text beside the number remaining. Default "Remaining".

Details

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().

Value

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.

Box text

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).

See Also

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()

Examples

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)

Describe a cohort flow in words, for a methods section

Description

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.

Usage

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, ...)

Arguments

flow

A cf_flow object produced by apply_criteria().

assessed_label

Text after the starting count in the first sentence, as in "Of 200 participants assessed for eligibility". Default "assessed for eligibility".

unit

Plural noun for what is counted, used verbatim (it is not pluralised or inflected). Default "participants".

count_by

Optional hierarchy level to count instead of rows, passed to as_attrition_tibble() (see there). Set unit to match.

big_mark

Thousands separator for counts ("1,234" with the default ","); "" turns grouping off.

digits

Decimal places for percentages. Default 1.

show_categories

Logical. When TRUE (default) steps with the same category are collapsed under a single parent row. When FALSE one row per step is produced.

drop_randomise

Logical. When TRUE, a randomise() step is ignored and everything is reported pooled, as if there were no arms. Default FALSE.

lowercase_reasons

Logical. When TRUE (default), the first letter of each reason is lower-cased so it reads mid-sentence ("Age missing" becomes "age missing"), unless the first word looks like an acronym (its second letter is upper case, as in "BMI missing"). Quoted labels (⁠not meeting "<label>"⁠) are never changed.

style

"prose" (default) for one paragraph, or "bullets" for one sentence per line, each starting "- " (Markdown list items).

x

A cf_narrative object.

...

Ignored.

Value

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.

Wording

  • 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 <assessed_label>, ..."; later ones open "A further ...". Each gives the number removed and its percentage of those entering that category or step, then the reason(s): one reason in brackets, several as a list with their own counts. The last sentence before randomisation (or before the final sentence) ends ", leaving 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.

See Also

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()

Examples

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)

Create an eligibility criteria pipeline

Description

cf_criteria() initialises an empty criteria pipeline. Use the pipe operators include(), exclude(), group_include(), group_exclude(), and select_within() to add steps.

Usage

cf_criteria(...)

Arguments

...

Optional cf_criterion objects to include at construction time.

Value

A cf_criteria object.

See Also

Other criteria builders: cf_criterion(), check_criteria(), exclude(), group_exclude(), group_include(), include(), randomise(), select_within()

Examples

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")

crit

Create a single cohort criterion

Description

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.

Usage

cf_criterion(
  predicate,
  label,
  type = c("include", "exclude", "group_include", "group_exclude", "select_within",
    "randomise"),
  by = NULL,
  category = NULL,
  arms = NULL,
  reason = NULL
)

Arguments

predicate

A one-sided formula or a function.

  • For include / exclude: evaluated row-wise; must return a logical vector of length nrow(data).

  • For group_include / group_exclude: evaluated in a dplyr::summarise() context per group (defined by by); must return a scalar logical. The result is broadcast back to all rows in each group.

  • For select_within: evaluated per group; must return a logical vector identifying which rows within the group to keep.

  • For randomise: must be NULL (a randomise step never removes rows).

Formula predicates are evaluated with a data mask, so the rlang pronouns work in every step type: .data$age always refers to the column and .env$age to a variable in the formula's environment, which avoids ambiguity when a column and a local variable share a name.

label

A short human-readable description of this criterion.

type

One of "include", "exclude", "group_include", "group_exclude", "select_within", or "randomise".

by

For grouped step types (group_include, group_exclude, select_within): one or more character strings naming the grouping column(s); supply more than one for composite (multi-column) grouping. For randomise: one or more character strings naming the randomisation unit column(s) (e.g. "cluster_id"). Must be NULL for the row-wise types (include, exclude). Rows with an NA in any by column cannot be assigned to a group and are always removed by grouped step types.

category

An optional character string grouping this criterion with others for display purposes (e.g. "Valid age" to group age-related steps into one box in a CONSORT diagram). NULL (default) leaves the step uncategorised (NA in output).

arms

For type = "randomise" only: a single character string naming the column in the data that holds each unit's allocated arm (e.g. "arm"). Used by as_consort_diagram()/as_attrition_tibble() to default branch_by when not explicitly supplied. Must be NULL for all other types.

reason

An optional short description of the rows this step removes, used wherever removals are listed: the exclusion boxes of as_consort_diagram(). NULL (default) falls back to label for the exclusion types (exclude, group_exclude), whose label already describes the removed rows. For include, group_include and select_within the label describes the rows kept, so set reason (e.g. ⁠label = "Aged 18 or over", reason = "Under 18"⁠). Must be NULL for randomise. See the Labels section of include().

Value

A cf_criterion object (an S3 list).

See Also

Other criteria builders: cf_criteria(), check_criteria(), exclude(), group_exclude(), group_include(), include(), randomise(), select_within()

Examples

# 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"
)

Declare the expected set of observational units

Description

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.

Usage

cf_expected(..., stringsAsFactors = FALSE)

Arguments

...

Named vectors of values, one per grouping variable, e.g. ⁠participant_id = 1:50, visit = c("baseline", "3mo", "6mo")⁠. At least one named argument is required.

stringsAsFactors

Passed to expand.grid(); default FALSE.

Value

A tibble with one row per expected combination and one column per named argument in ....

See Also

Other pipeline: apply_criteria(), cf_hierarchy(), continue_criteria()

Examples

cf_expected(participant_id = 1:3, visit = c("baseline", "3mo"))

Declare the nesting hierarchy for a cohort

Description

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.

Usage

cf_hierarchy(...)

Arguments

...

Named arguments mapping role labels to column names, e.g. ⁠participant = "participant_id", cluster = "cluster_id"⁠. A role's value may be a character vector of more than one column when the level is a composite (multi-column) key, e.g. cluster_period = c("cluster_id", "period") for a stepped-wedge design. At least one entry is required.

Details

The order of ... is from the finest (innermost) level to the coarsest (outermost) level. The first role is conventionally the individual participant.

Value

A cf_hierarchy object (a named list with additional class attribute).

See Also

Other pipeline: apply_criteria(), cf_expected(), continue_criteria()

Examples

# 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")

Check that criteria only refer to columns present in the data

Description

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⁠.

Usage

check_criteria(criteria, data)

Arguments

criteria

A cf_criteria object.

data

A data frame.

Details

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.

Value

NULL, invisibly. Called for its side effect of aborting when a criterion refers to a column not in data.

What is checked

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.

See Also

apply_criteria(), continue_criteria().

Other criteria builders: cf_criteria(), cf_criterion(), exclude(), group_exclude(), group_include(), include(), randomise(), select_within()

Examples

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))

Extract the surviving cohort from a flow object

Description

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.

Usage

cohort(
  flow,
  flag = FALSE,
  at = NULL,
  step_number = NULL,
  label = NULL,
  category = NULL
)

Arguments

flow

A cf_flow object produced by apply_criteria().

flag

Logical. When FALSE (default), returns only the surviving rows (the historical behaviour). When TRUE, returns all original rows, in their original order, with attribution columns added instead of filtering: cf_included (logical), cf_excluded_step (integer, NA if included), cf_excluded_label (character, NA if included), and cf_excluded_category (character, NA if uncategorised or included). Useful when downstream code needs every row present (e.g. plotting a full recording) while still knowing which rows count. Combined with a step selector, attribution only considers steps up to that step; rows removed later count as included.

at

Optional automatic step selector (number, label or category); see the section "Intermediate steps".

step_number

Optional whole step number (0 = starting data).

label

Optional exact step label.

category

Optional category name (last step in that category).

Value

A tibble.

Intermediate steps

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.

See Also

criteria_status() for each row's result on every criterion.

Other flow accessors: criteria_status(), excluded(), stack_cohorts()

Examples

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-2

Continue a criteria pipeline on top of an existing flow

Description

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).

Usage

continue_criteria(flow, criteria, join = NULL, by = NULL)

Arguments

flow

A cf_flow object produced by apply_criteria() (or a previous call to continue_criteria()).

criteria

A cf_criteria object with the additional steps to apply. If empty (length(criteria) == 0), flow is returned unchanged.

join

Optional data frame of new columns to attach before evaluating criteria, e.g. follow-up data collected after the initial screening. Joined onto all of flow's original rows (via a left join), so rows already excluded at an earlier stage also gain the new columns (as NA where join has no match) – this keeps the full row history intact. Requires by.

by

Column name(s) shared by flow's data and join, used to join them. Required, and only used, when join is supplied.

Details

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).

Value

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.

See Also

Other pipeline: apply_criteria(), cf_expected(), cf_hierarchy()

Examples

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)
flow2

Per-criterion status of every row

Description

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().

Usage

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")
)

Arguments

flow

A cf_flow object produced by apply_criteria().

mode

"cumulative" (default) or "independent"; see the section "Modes".

sets

"pass" (default) reports whether each row passed each criterion; "fail" negates every criterion column (NA stays NA), so TRUE marks the reasons a row fails.

na

What to do with NA in the criterion columns, applied after sets: "keep" (default) leaves them; "false" replaces them with FALSE; "drop" removes rows with any NA.

names

Criterion column names: "label" (default) uses step labels, made unique with a warning if repeated; "step" uses ⁠cf_step_<n>⁠. A name that clashes with an id or data column is made unique with a warning.

drop_randomise

Logical. Omit randomise() steps (default TRUE).

keep_data

Logical. Include the original data columns between the id column(s) and the criterion columns (default FALSE).

as

Return type: "tibble" (default), "data.table" (requires the data.table package), or "matrix", a logical matrix of the criterion columns only, with the row identifier as row names (keep_data is ignored).

Value

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.

Modes

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 plots

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))

See Also

cohort() for the cohort itself, excluded() for removed rows.

Other flow accessors: cohort(), excluded(), stack_cohorts()

Examples

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

Description

Add an exclusion criterion to a criteria pipeline

Usage

exclude(criteria, predicate, label, category = NULL, reason = NULL)

Arguments

criteria

A cf_criteria object (or NULL to start a new one).

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. NULL leaves it uncategorised.

reason

An optional short description of the rows this step removes, shown in diagram exclusion boxes. NULL (default) uses label for exclusion steps; for inclusion steps it should be set. See the Labels section.

Value

The updated cf_criteria object.

Missing values

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".

Labels

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.

See Also

Other criteria builders: cf_criteria(), cf_criterion(), check_criteria(), group_exclude(), group_include(), include(), randomise(), select_within()

Examples

cf_criteria() |>
  include(~ !is.na(consent_date), label = "Consent recorded", category = "Consent") |>
  exclude(~ withdrew, label = "Withdrew consent", category = "Consent")

Extract excluded rows from a flow object

Description

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.

Usage

excluded(
  flow,
  at = NULL,
  step_number = NULL,
  label = NULL,
  category = NULL,
  only = FALSE
)

Arguments

flow

A cf_flow object produced by apply_criteria().

at

Optional automatic step selector (number, label or category); see the section "Intermediate steps".

step_number

Optional whole step number (0 = starting data).

label

Optional exact step label.

category

Optional category name (last step in that category).

only

Logical. When FALSE (default), returns rows removed by every step up to and including the selected step. When TRUE, returns only the rows removed at the selected step (for a category selector, the last step in that category). Step 0 removes nothing, so ⁠step_number = 0, only = TRUE⁠ returns no rows. With no selector, TRUE gives the rows removed at the last step.

Value

A tibble with original columns plus cf_step, cf_label, cf_type, cf_category.

Intermediate steps

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.

See Also

Other flow accessors: cohort(), criteria_status(), stack_cohorts()

Examples

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)

Export a criteria pipeline to YAML

Description

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().

Usage

export_criteria(criteria, path = NULL, fn_refs = list())

Arguments

criteria

A cf_criteria object.

path

A file path to write to. If NULL (default), the YAML text is returned as a character string.

fn_refs

An optional named list mapping function objects to "pkg::name" reference strings.

Value

When path = NULL, the YAML text as a character string (returned visibly, so it prints at the console). Otherwise, invisibly, the criteria object.

YAML schema

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.

See Also

import_criteria() to read the file back.

Other yaml: import_criteria()

Examples

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)

Add a group-level exclusion criterion

Description

The predicate is evaluated per group; groups where the predicate returns TRUE are removed (all their rows dropped).

Usage

group_exclude(criteria, by, predicate, label, category = NULL, reason = NULL)

Arguments

criteria

A cf_criteria object (or NULL to start a new one).

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. NULL leaves it uncategorised.

reason

An optional short description of the rows this step removes, shown in diagram exclusion boxes. NULL (default) uses label for exclusion steps; for inclusion steps it should be set. See the Labels section.

Value

The updated cf_criteria object.

See Also

Other criteria builders: cf_criteria(), cf_criterion(), check_criteria(), exclude(), group_include(), include(), randomise(), select_within()

Examples

cf_criteria() |>
  group_exclude(by = "cluster_id", ~ mean(is.na(age)) > 0.5,
                label = "Excessive missing age in cluster")

Add a group-level inclusion criterion

Description

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.

Usage

group_include(criteria, by, predicate, label, category = NULL, reason = NULL)

Arguments

criteria

A cf_criteria object (or NULL to start a new one).

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 (n(), mean(), n_distinct(), etc.) or a function that receives a grouped data frame and returns a tibble with columns ⁠<by>⁠ and .pass.

label

A short human-readable description of this criterion.

category

An optional string grouping this step with others for display. NULL leaves it uncategorised.

reason

An optional short description of the rows this step removes, shown in diagram exclusion boxes. NULL (default) uses label for exclusion steps; for inclusion steps it should be set. See the Labels section.

Value

The updated cf_criteria object.

See Also

Other criteria builders: cf_criteria(), cf_criterion(), check_criteria(), exclude(), group_exclude(), include(), randomise(), select_within()

Examples

cf_criteria() |>
  group_include(by = "cluster_id", ~ n() >= 5, label = "Cluster size >= 5")

Import a criteria pipeline from YAML

Description

Reads a YAML file (or string) written by export_criteria() and reconstructs a cf_criteria object.

Usage

import_criteria(path = NULL, text = NULL, envir = parent.frame())

Arguments

path

A file path to read from. Exactly one of path or text must be supplied.

text

A YAML string. Exactly one of path or text must be supplied.

envir

The environment in which to evaluate re-parsed expressions.

Value

A cf_criteria object.

Security

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.

See Also

export_criteria() to write a pipeline.

Other yaml: export_criteria()

Examples

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

Description

Add an inclusion criterion to a criteria pipeline

Usage

include(criteria, predicate, label, category = NULL, reason = NULL)

Arguments

criteria

A cf_criteria object (or NULL to start a new one).

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. "Valid age"). NULL leaves it uncategorised.

reason

An optional short description of the rows this step removes, shown in diagram exclusion boxes. NULL (default) uses label for exclusion steps; for inclusion steps it should be set. See the Labels section.

Value

The updated cf_criteria object.

Missing values

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".

Labels

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.

See Also

Other criteria builders: cf_criteria(), cf_criterion(), check_criteria(), exclude(), group_exclude(), group_include(), randomise(), select_within()

Examples

cf_criteria() |>
  include(~ age >= 18, label = "Adults", category = "Valid age",
          reason = "Under 18")

Generate synthetic data for a cluster-randomised controlled trial

Description

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.

Usage

mock_cluster_rct(
  n_clusters = 12L,
  n_participants = 480L,
  n_sites = 3L,
  arm_labels = c("Control", "Intervention"),
  seed = 123L
)

Arguments

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 <= n_clusters).

arm_labels

Character vector. Labels for the trial arms; clusters are allocated to these labels with balanced randomisation.

seed

Integer. Random seed for reproducibility.

Value

A tibble::tibble() with one row per participant, including participant_id, cluster_id, site_id, arm (cluster-level), demographic columns, and consent-flow columns.

See Also

Other mock data: mock_crossover(), mock_parallel_rct(), mock_stepped_wedge()

Examples

mock_cluster_rct()
mock_cluster_rct(n_clusters = 20, n_participants = 800, seed = 5)

Generate synthetic cohort data for testing and examples (deprecated)

Description

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.

Usage

mock_cohortflow(
  n_participants = 500L,
  n_clusters = 10L,
  n_sites = 3L,
  n_periods = 4L,
  seed = 123L
)

Arguments

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_clusters).

n_periods

Integer. Number of time periods (e.g., waves in a stepped-wedge design). Set to 1 for a simple cross-sectional cohort.

seed

Integer. Random seed for reproducibility.

Value

A tibble::tibble() with columns:

participant_id

Character. Unique participant identifier.

event_id

Character. Unique event (row) identifier – useful when the dataset has multiple rows per participant (e.g., one per operation).

cluster_id

Character. Cluster identifier.

site_id

Character. Site identifier (clusters nested in sites).

period

Integer. Study period (1 = first period).

sequence

Integer. Stepped-wedge sequence the cluster is assigned to (NA if n_periods == 1).

age

Numeric. Age in years (some NAs to simulate missing data).

age_group

Character. Age group ("<18", "18-39", "40-64", "65+").

sex

Character. "M" / "F" / "O" (other).

ethnicity

Character. One of five broad ethnic groups.

consent_date

Date. Date of consent (NA = did not consent).

baseline_complete

Logical. Whether the baseline assessment is complete.

withdrew

Logical. Whether the participant withdrew after consent.

eligible_screen

Logical. Whether the participant passed initial eligibility screening (e.g., diagnosis confirmed).

Examples

mock_cohortflow()

# Larger study with three periods
mock_cohortflow(n_participants = 2000, n_clusters = 20, n_periods = 3, seed = 42)

Generate synthetic data for a crossover trial

Description

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.

Usage

mock_crossover(n_participants = 120L, arm_labels = c("A", "B"), seed = 123L)

Arguments

n_participants

Integer. Number of participants.

arm_labels

Character vector. Labels for the treatments being crossed over. Determines both the number of periods (length(arm_labels)) and the number of possible sequences (all permutations of arm_labels).

seed

Integer. Random seed for reproducibility.

Value

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.

See Also

Other mock data: mock_cluster_rct(), mock_parallel_rct(), mock_stepped_wedge()

Examples

mock_crossover()
mock_crossover(n_participants = 60, arm_labels = c("Drug", "Placebo"), seed = 3)

Generate synthetic data for a parallel-group randomised controlled trial

Description

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.

Usage

mock_parallel_rct(
  n_participants = 300L,
  arm_labels = c("Control", "Intervention"),
  seed = 123L
)

Arguments

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.

Value

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).

See Also

Other mock data: mock_cluster_rct(), mock_crossover(), mock_stepped_wedge()

Examples

mock_parallel_rct()
mock_parallel_rct(n_participants = 300, arm_labels = c("Placebo", "Drug"), seed = 7)

Generate synthetic data for a stepped-wedge cluster-randomised trial

Description

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.

Usage

mock_stepped_wedge(
  n_clusters = 12L,
  n_participants = 480L,
  n_periods = 4L,
  n_sites = 3L,
  arm_labels = c("Control", "Intervention"),
  seed = 123L
)

Arguments

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 <= n_clusters).

arm_labels

Character vector of length 2: c(control_label, intervention_label).

seed

Integer. Random seed for reproducibility.

Value

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.

See Also

Other mock data: mock_cluster_rct(), mock_crossover(), mock_parallel_rct()

Examples

mock_stepped_wedge()
mock_stepped_wedge(n_clusters = 8, n_participants = 400, n_periods = 5, seed = 9)

Plot method for cf_flow objects

Description

A thin wrapper around as_consort_diagram() so that plot(flow) draws a CONSORT flow diagram directly from a cf_flow object.

Usage

## S3 method for class 'cf_flow'
plot(x, ...)

Arguments

x

A cf_flow object produced by apply_criteria().

...

Additional arguments passed on to as_consort_diagram().

Value

A consort_diagram object, invisibly printed.

Examples

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")

Print method for consort_diagram objects

Description

Draws 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).

Usage

## S3 method for class 'consort_diagram'
print(x, ...)

Arguments

x

A consort_diagram object.

...

Additional arguments passed on to ggplot2::print.ggplot().

Value

x, invisibly.

Examples

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)

Mark the randomisation/allocation point in a criteria pipeline

Description

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.

Usage

randomise(criteria, by, arms, label = "Randomised", category = NULL)

Arguments

criteria

A cf_criteria object (or NULL to start a new one).

by

One or more column names (character vector) naming the randomisation unit (e.g. "cluster_id" for cluster randomisation, or the participant id for individual randomisation).

arms

A single column name (string) holding each unit's allocated arm (e.g. "arm").

label

A short human-readable description of this step. Default "Randomised" (unlike other builders, a label is not required).

category

An optional string grouping this step with others for display. NULL leaves it uncategorised.

Value

The updated cf_criteria object.

See Also

Other criteria builders: cf_criteria(), cf_criterion(), check_criteria(), exclude(), group_exclude(), group_include(), include(), select_within()

Examples

cf_criteria() |>
  include(~ eligible, label = "Eligible clusters") |>
  randomise(by = "cluster_id", arms = "arm") |>
  exclude(~ withdrew, label = "Withdrew after allocation")

Save a CONSORT diagram for manuscript submission

Description

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.

Usage

save_consort_diagram(
  diagram,
  path,
  width = NULL,
  height = NULL,
  units = c("in", "cm", "mm", "px"),
  dpi = 300,
  ...
)

Arguments

diagram

A consort_diagram from as_consort_diagram(), or a cf_flow, which is drawn with as_consort_diagram(diagram)'s defaults. Build the diagram yourself to customise it.

path

File to write. The extension (.png, .tiff/.tif, .jpeg/.jpg, .pdf, .svg or .eps, case-insensitive) picks the format.

width, height

Plot size in units. NULL (default) derives it from the diagram layout; see Details.

units

Units of width and height: "in", "cm", "mm" or "px".

dpi

Resolution for raster formats. Default 300.

...

Further arguments passed to ggplot2::ggsave(), e.g. bg = "transparent" (the default background is "white") or ⁠device =⁠ to override the device choice.

Details

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.

Value

path, invisibly.

See Also

as_consort_diagram()

Other reporting: as_attrition_table(), as_attrition_tibble(), as_characteristics_table(), as_characteristics_tibble(), as_consort_diagram(), as_narrative()

Examples

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))

Select rows within groups

Description

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.

Usage

select_within(criteria, by, predicate, label, category = NULL, reason = NULL)

Arguments

criteria

A cf_criteria object (or NULL to start a new one).

by

One or more column names (character vector) defining the grouping (e.g. "participant_id"); supply more than one for composite (multi-column) grouping.

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. NULL leaves it uncategorised.

reason

An optional short description of the rows this step removes, shown in diagram exclusion boxes. NULL (default) uses label for exclusion steps; for inclusion steps it should be set. See the Labels section.

Value

The updated cf_criteria object.

See Also

Other criteria builders: cf_criteria(), cf_criterion(), check_criteria(), exclude(), group_exclude(), group_include(), include(), randomise()

Examples

cf_criteria() |>
  select_within(by = "participant_id",
                ~ consent_date == min(consent_date, na.rm = TRUE),
                label = "Index operation per patient")

Stack the cohort at each step into one data frame

Description

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.

Usage

stack_cohorts(
  flow,
  steps = NULL,
  excluded = FALSE,
  level = NULL,
  drop_randomise = TRUE,
  assessed_label = "Assessed for eligibility"
)

Arguments

flow

A cf_flow object produced by apply_criteria().

steps

Optional step selectors (a vector or list); see the section "Steps". NULL (default) means every step.

excluded

Logical. FALSE (default) describes the cohort surviving each step; TRUE describes the rows removed at each step.

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 randomise() steps when steps is NULL (default TRUE).

assessed_label

Heading for step 0, the starting data. Default "Assessed for eligibility".

Value

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.

Steps

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>".

Hierarchy levels

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.

See Also

as_characteristics_tibble(), cohort(), excluded().

Other flow accessors: cohort(), criteria_status(), excluded()

Examples

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)