### Install CohortConstructor Development Version from GitHub Source: https://ohdsi.github.io/CohortConstructor/index.html Install the latest development version of CohortConstructor directly from GitHub using the devtools package. ```r # install.packages("devtools") devtools::install_github("ohdsi/CohortConstructor") ``` -------------------------------- ### Generate Initial Concept-Based Cohort Source: https://ohdsi.github.io/CohortConstructor/index.html Create a cohort based on a provided codelist. This example sets the cohort exit date to the same day as the event start date. ```r cdm$fractures <- cdm |> conceptCohort(conceptSet = fx_codes, exit = "event_start_date", name = "fractures") ``` -------------------------------- ### Install CohortConstructor from CRAN Source: https://ohdsi.github.io/CohortConstructor/index.html Use this command to install the stable version of the CohortConstructor package from CRAN. ```r install.packages("CohortConstructor") ``` -------------------------------- ### Create a cohort with custom exit and overlap rules Source: https://ohdsi.github.io/CohortConstructor/reference/conceptCohort.html This example shows how to create a cohort named 'study_cohort' using multiple concept IDs for 'nitrogen' and 'potassium'. It specifies that the cohort exit date should be the event start date and that overlapping records should extend the cohort duration. It also subsets the cohort based on an existing 'cohort'. ```r conceptSet <- list( "nitrogen" = c(35604434, 35604439), "potassium" = c(40741270, 42899580, 44081436) ) cdm$study_cohort <- conceptCohort(cdm = cdm, conceptSet = conceptSet, name = "study_cohort", exit = "event_start_date", overlap = "extend", subsetCohort = "cohort") cdm$study_cohort |> attrition() ``` -------------------------------- ### Mock CDM Setup for Measurement Cohort Source: https://ohdsi.github.io/CohortConstructor/reference/measurementCohort.html Sets up a mock CDM database with vocabulary and measurement tables. This is a prerequisite for creating cohorts based on measurement data. ```r library(CohortConstructor) library(omock) library(dplyr) cdm <- mockVocabularyTables(concept = tibble( concept_id = c(4326744, 4298393, 45770407, 8876, 4124457), concept_name = c("Blood pressure", "Systemic blood pressure", "Baseline blood pressure", "millimeter mercury column", "Normal range"), domain_id = "Measurement", vocabulary_id = c("SNOMED", "SNOMED", "SNOMED", "UCUM", "SNOMED"), standard_concept = "S", concept_class_id = c("Observable Entity", "Observable Entity", "Observable Entity", "Unit", "Qualifier Value"), concept_code = NA_character_, valid_start_date = as.Date(NA_character_), valid_end_date = as.Date(NA_character_), invalid_reason = NA_character_ )) |> mockCdmFromTables(tables = list( measurement = tibble( measurement_id = 1:4L, person_id = c(1L, 1L, 2L, 3L), measurement_concept_id = c(4326744L, 4298393L, 4298393L, 45770407L), measurement_date = as.Date(c("2000-07-01", "2000-12-11", "2002-09-08", "2015-02-19")), measurement_type_concept_id = 0L, value_as_number = c(100, 125, NA, NA), value_as_concept_id = c(0L, 0L, 0L, 4124457L), unit_concept_id = c(8876L, 8876L, 0L, 0L) ) )) ``` -------------------------------- ### mockCohortConstructor() Source: https://ohdsi.github.io/CohortConstructor/reference/mockCohortConstructor.html Creates an example CDM dataset for demonstrating and testing the CohortConstructor package. It allows specifying the data source and a seed for reproducibility. ```APIDOC ## Function: mockCohortConstructor ### Description Creates an example dataset that can be used for demonstrating and testing the CohortConstructor package. ### Usage ```R mockCohortConstructor(source = "local", seed = 1) ``` ### Arguments * **source** (character) - Source for the mock cdm, it can either be 'local' or 'duckdb'. * **seed** (integer or NULL) - An optional integer used to set the seed for random number generation, ensuring reproducibility of the generated data. If provided, this seed allows the function to produce consistent results each time. If 'NULL', the seed is not set, which can lead to different outputs on each run. ### Value An object of class 'cdm' representing the mock CDM. ### Examples ```R # Load the CohortConstructor package library(CohortConstructor) # Create a mock CDM object from a local source with a specific seed cdm <- mockCohortConstructor(source = "local", seed = 1) # Print the CDM object to see its structure print(cdm) ``` ``` -------------------------------- ### padCohortStart Source: https://ohdsi.github.io/CohortConstructor/reference/padCohortStart.html Adds (or subtracts) a certain number of days to the cohort start date. Note: If the days added means that cohort start would be after cohort end then the cohort entry will be dropped. If subtracting day means that cohort start would be before observation period start then the cohort entry will be dropped. ```APIDOC ## padCohortStart() ### Description Adds (or subtracts) a certain number of days to the cohort start date. Note: * If the days added means that cohort start would be after cohort end then the cohort entry will be dropped. * If subtracting day means that cohort start would be before observation period start then the cohort entry will be dropped. ### Method ```R padCohortStart( cohort, days, collapse = TRUE, requireFullContribution = FALSE, cohortId = NULL, name = tableName(cohort), .softValidation = FALSE ) ``` ### Arguments * **cohort** (ANY) - A cohort table in a cdm reference. * **days** (numeric) - Integer with the number of days to add or name of a column (that must be numeric) to add. * **collapse** (logical) - Whether to collapse the overlapping records (TRUE) or drop the records that have an ongoing prior record. * **requireFullContribution** (logical) - Whether to require individuals to contribute all required days. If TRUE, those individuals for which adding days would take them out of observation will be dropped. If FALSE, days will only be added up to the day when the individual leaves observation. * **cohortId** (ANY) - Vector identifying which cohorts to modify (cohort_definition_id or cohort_name). If NULL, all cohorts will be used; otherwise, only the specified cohorts will be modified, and the rest will remain unchanged. * **name** (ANY) - Name of the new cohort table created in the cdm object. * **.softValidation** (logical) - Whether to perform a soft validation of consistency. If set to FALSE four additional checks will be performed: 1) a check that cohort end date is not before cohort start date, 2) a check that there are no missing values in required columns, 3) a check that cohort duration is all within observation period, and 4) that there are no overlapping cohort entries ### Value Cohort table ### Examples ```R # \donttest{ library(CohortConstructor) cdm <- mockCohortConstructor() # add 10 days to each cohort entry cdm$cohort1 %>% padCohortStart(days = 10) # } ``` ``` -------------------------------- ### Load Libraries and Mock CDM Data Source: https://ohdsi.github.io/CohortConstructor/articles/a07_filter_cohorts.html Loads necessary R libraries and creates a mock CDM database for examples. ```r library(omock) library(dplyr) library(CohortConstructor) library(CohortCharacteristics) library(ggplot2) ``` ```r cdm <- mockCdmFromDataset(datasetName = "GiBleed", source = "duckdb") ``` -------------------------------- ### Example: Using exitAtFirstDate with multiple date columns Source: https://ohdsi.github.io/CohortConstructor/reference/exitAtFirstDate.html This example demonstrates how to use `exitAtFirstDate` to set the cohort end date based on the earliest of 'next_obs' and 'future_observation' columns. It requires the 'CohortConstructor' and 'PatientProfiles' libraries and a mock CDM object. ```r # \donttest{ library(CohortConstructor) library(PatientProfiles) cdm <- mockCohortConstructor() #> ℹ Reading GiBleed tables. cdm$cohort1 <- cdm$cohort1 |> addTableIntersectDate(tableName = "observation", nameStyle = "next_obs", order = "first") |> addFutureObservation(futureObservationType = "date", name = "cohort1") cdm$cohort1 | exitAtFirstDate(dateColumns = c("next_obs", "future_observation")) #> Warning: The `name` argument was not provided. #> ℹ The original "cohort1" table will be overwritten. #> ℹ To avoid this, set `name = ''` in your function call. #> # A tibble: 54 × 6 #> cohort_definition_id subject_id cohort_start_date cohort_end_date next_obs #> #> 1 1 1 2005-05-25 2005-12-06 2005-12-06 #> 2 1 2 1987-06-29 1987-07-09 1987-07-09 #> 3 1 6 2014-03-30 2014-05-25 2014-05-25 #> 4 1 7 2018-04-07 2018-04-12 2018-04-12 #> 5 1 10 2008-12-27 2009-04-27 2009-04-27 #> 6 1 13 2010-12-10 2011-02-20 2011-02-20 #> 7 1 14 1995-02-12 1995-02-23 1995-02-23 #> 8 1 15 2009-04-01 2009-04-07 2009-04-07 #> 9 1 17 2008-06-28 2009-01-07 2009-01-07 #> 10 1 18 2019-08-14 2019-08-14 2019-08-14 #> # ℹ 44 more rows #> # ℹ 1 more variable: future_observation # } ``` -------------------------------- ### Create Mock CDM Reference Source: https://ohdsi.github.io/CohortConstructor/reference/mockCohortConstructor.html Generates an example CDM object for testing CohortConstructor. The 'source' argument can be 'local' or 'duckdb', and an optional 'seed' can be provided for reproducibility. ```r library(CohortConstructor) cdm <- mockCohortConstructor() ``` -------------------------------- ### Load Required Libraries Source: https://ohdsi.github.io/CohortConstructor/articles/a02_cohort_table_requirements.html Loads the necessary R packages for cohort construction and analysis. Ensure these packages are installed before running. ```r library(omock) library(CodelistGenerator) library(CohortConstructor) library(CohortCharacteristics) library(ggplot2) library(dplyr) ``` -------------------------------- ### Load Libraries and Mock CDM Source: https://ohdsi.github.io/CohortConstructor/articles/a12_behind_the_scenes.html Loads necessary R packages and creates a mock CDM reference using Eunomia for demonstration purposes. This setup is required before using CohortConstructor functions. ```r library(omock) library(CodelistGenerator) library(PatientProfiles) library(CohortConstructor) library(dplyr) cdm <- mockCdmFromDataset(datasetName = "GiBleed", source = "duckdb") ``` -------------------------------- ### Log SQL for Compute Type (Filter Start Date Null) Source: https://ohdsi.github.io/CohortConstructor/articles/a12_behind_the_scenes.html Logs a SQL query of type 'compute' that filters records where the cohort start date is not null. Includes schema, table prefix, and overwrite settings. ```sql SELECT * FROM results.test_drugs WHERE (NOT((cohort_start_date IS NULL))) ``` -------------------------------- ### Set Cohort End Date by Adding Days Source: https://ohdsi.github.io/CohortConstructor/reference/padCohortDate.html This example demonstrates how to extend the cohort end date by adding 10 days, using the cohort start date as the reference. It overwrites the original cohort table if a new name is not provided. ```r library(CohortConstructor) cdm <- mockCohortConstructor() cdm$cohort1 |> padCohortDate( cohortDate = "cohort_end_date", indexDate = "cohort_start_date", days = 10) ``` -------------------------------- ### Create cohorts using a subset of individuals Source: https://ohdsi.github.io/CohortConstructor/reference/measurementCohort.html This example demonstrates creating cohorts based on measurement records only for individuals present in a pre-existing 'diabetes_patients' cohort. ```r measurementCohort( cdm, conceptSet = glucose, name = "glucose_in_diabetes_patients", subsetCohort = "diabetes_patients" ) ``` -------------------------------- ### Create Multiple Cohorts with Prior Observation Source: https://ohdsi.github.io/CohortConstructor/reference/demographicsCohort.html This example shows how to create multiple demographic cohorts simultaneously, with different age ranges and sexes, and also applies a minimum prior observation requirement. It uses mock data for demonstration. ```r cohort <- cdm |> demographicsCohort(name = "cohort4", ageRange = list(c(0, 19),c(20, 64),c(65, 150)), sex = c("Male", "Female", "Both"), minPriorObservation = 365) attrition(cohort) ``` -------------------------------- ### Compute Cohort Start and End Dates Source: https://ohdsi.github.io/CohortConstructor/articles/a12_behind_the_scenes.html Computes the cohort start and end dates from the 'test_drugs' table. It handles cases where start and end dates might be inverted, ensuring a valid date range. ```sql SELECT cohort_definition_id, subject_id, cohort_start_date, CASE WHEN (cohort_start_date <= cohort_end_date) THEN cohort_end_date WHEN NOT (cohort_start_date <= cohort_end_date) THEN cohort_start_date END AS cohort_end_date FROM results.test_drugs ``` -------------------------------- ### Log SQL Query: Detect End Before Start Dates Source: https://ohdsi.github.io/CohortConstructor/articles/a12_behind_the_scenes.html This snippet logs a query to identify records in 'test_drugs' where the cohort end date is before the cohort start date. This is useful for data validation. ```sql SELECT * FROM ( SELECT subject_id, CASE WHEN (cohort_end_date < cohort_start_date) THEN 1 WHEN NOT (cohort_end_date < cohort_start_date) THEN 0 END AS end_before_start FROM results.test_drugs ) AS q01 WHERE (end_before_start = 1) ``` -------------------------------- ### Log SQL for Compute Type (Filter Start Date) Source: https://ohdsi.github.io/CohortConstructor/articles/a12_behind_the_scenes.html Logs a SQL query of type 'compute' that filters records based on the cohort start date relative to observation period end dates. Includes schema, table prefix, and overwrite settings. ```sql SELECT cohort_definition_id, subject_id, cohort_start_date, CASE WHEN (observation_period_end_date >= cohort_end_date) THEN cohort_end_date WHEN NOT (observation_period_end_date >= cohort_end_date) THEN observation_period_end_date END AS cohort_end_date FROM results.test_drugs WHERE (cohort_start_date >= observation_period_start_date) AND (cohort_start_date <= observation_period_end_date) ``` -------------------------------- ### Example: Setting Cohort End Date using entryAtLastDate Source: https://ohdsi.github.io/CohortConstructor/reference/entryAtLastDate.html This example demonstrates how to use the entryAtLastDate function to set the cohort end date based on the latest date from 'prior_drug' and 'prior_observation' columns. It first adds these date columns to the cohort using addTableIntersectDate and addPriorObservation. ```r # \donttest{ library(CohortConstructor) library(PatientProfiles) cdm <- mockCohortConstructor() #> ℹ Reading GiBleed tables. cdm$cohort1 <- cdm$cohort1 |> addTableIntersectDate( tableName = "drug_exposure", nameStyle = "prior_drug", order = "last", window = c(-Inf, 0) ) |> addPriorObservation(priorObservationType = "date", name = "cohort1") cdm$cohort1 |> entryAtLastDate(dateColumns = c("prior_drug", "prior_observation")) #> Warning: The `name` argument was not provided. #> ℹ The original "cohort1" table will be overwritten. #> ℹ To avoid this, set `name = ''` in your function call. #> # A tibble: 54 × 6 #> cohort_definition_id subject_id cohort_start_date cohort_end_date prior_drug #> #> 1 1 1 2005-05-12 2006-08-20 2005-05-12 #> 2 1 2 1987-05-27 1990-01-03 1987-05-27 #> 3 1 6 2014-03-26 2015-02-21 2014-03-26 #> 4 1 7 2018-04-07 2018-04-25 2018-04-07 #> 5 1 10 2008-11-30 2010-04-02 2008-11-30 #> 6 1 13 2010-12-04 2011-06-29 2010-12-04 #> 7 1 14 1995-02-11 2002-11-12 1995-02-11 #> 8 1 15 2009-04-01 2009-11-09 2009-04-01 #> 9 1 17 2008-06-20 2008-12-28 2008-06-20 #> 10 1 18 2019-08-14 2019-08-15 2019-08-14 #> # ℹ 44 more rows #> # ℹ 1 more variable: prior_observation # } ``` -------------------------------- ### entryAtFirstDate Source: https://ohdsi.github.io/CohortConstructor/reference/entryAtFirstDate.html Resets cohort start date based on a set of specified column dates. The first date that occurs is chosen. ```APIDOC ## entryAtFirstDate() ### Description Resets cohort start date based on a set of specified column dates. The first date that occurs is chosen. ### Usage ```R entryAtFirstDate( cohort, dateColumns, cohortId = NULL, returnReason = FALSE, keepDateColumns = TRUE, name = tableName(cohort), .softValidation = FALSE ) ``` ### Arguments * `cohort` (cohort table): A cohort table in a cdm reference. * `dateColumns` (character vector): Character vector indicating date columns in the cohort table to consider. * `cohortId` (vector, optional): Vector identifying which cohorts to modify (cohort_definition_id or cohort_name). If NULL, all cohorts will be used; otherwise, only the specified cohorts will be modified, and the rest will remain unchanged. * `returnReason` (logical): If TRUE it will return a column indicating which of the `dateColumns` was used. * `keepDateColumns` (logical): If TRUE the returned cohort will keep columns in `dateColumns`. * `name` (string): Name of the new cohort table created in the cdm object. * `.softValidation` (logical): Whether to perform a soft validation of consistency. If set to FALSE four additional checks will be performed: 1) a check that cohort end date is not before cohort start date, 2) a check that there are no missing values in required columns, 3) a check that cohort duration is all within observation period, and 4) that there are no overlapping cohort entries. ### Value The cohort table. ### Examples ```R # \donttest{ library(CohortConstructor) library(PatientProfiles) cdm <- mockCohortConstructor() cdm$cohort1 <- cdm$cohort1 %>% addTableIntersectDate( tableName = "drug_exposure", nameStyle = "prior_drug", order = "last", window = c(-Inf, 0) ) %>% addPriorObservation(priorObservationType = "date", name = "cohort1") cdm$cohort1 %>% entryAtFirstDate(dateColumns = c("prior_drug", "prior_observation")) # } ``` ``` -------------------------------- ### Create cohorts based on measurement values (concept IDs) Source: https://ohdsi.github.io/CohortConstructor/reference/measurementCohort.html This example demonstrates how to create two distinct cohorts, 'high_bmi' and 'low_bmi', by filtering measurements associated with specific concept IDs from a given 'bmi' concept set. ```r measurementCohort( cdm, conceptSet = bmi, name = "bmi_cohort", valueAsConcept = list(high_bmi = c(4328749, 35819253), low_bmi = c(4267416, 45881666)) ) ``` -------------------------------- ### Create a Codelist Object Source: https://ohdsi.github.io/CohortConstructor/index.html Combine concept IDs into a codelist object that can be used for cohort definition. This example creates a codelist for hip and forearm fractures. ```r fx_codes <- newCodelist(list("hip_fracture" = hip_fx_codes$concept_id, "forearm_fracture"= forearm_fx_codes$concept_id)) ``` -------------------------------- ### Create cohorts based on measurement values (numeric ranges) Source: https://ohdsi.github.io/CohortConstructor/reference/measurementCohort.html This example shows how to create a 'low_weight' cohort by filtering measurements within specified numeric ranges for different unit concept IDs (kilograms and stones). ```r measurementCohort( cdm, conceptSet = weight, name = "weight_cohort", valueAsNumber = list("low_weight" = list("9529" = c(30, 40), "21498905" = c(4.7, 6.3))) ) ``` -------------------------------- ### Create cohorts using both concept and numeric value filters Source: https://ohdsi.github.io/CohortConstructor/reference/measurementCohort.html This example illustrates creating a 'normal_bmi' cohort by filtering measurements that are both within a specified concept set and fall within a particular numeric range. ```r measurementCohort( cdm, conceptSet = bmi, name = "normal_bmi_cohort", valueAsConcept = list(normal_bmi = c(4328749, 35819253)), valueAsNumber = list("normal_bmi" = list("9529" = c(18.5, 25))) ) ``` -------------------------------- ### Create cohorts using specific type concept IDs Source: https://ohdsi.github.io/CohortConstructor/reference/measurementCohort.html This example shows how to create cohorts by filtering measurement records that match a specific type concept ID, such as 'Laboratory resulting' (32031). ```r measurementCohort( cdm, conceptSet = lab_tests, name = "lab_results", typeConceptId = 32031 ) ``` -------------------------------- ### Filter Cohort Entries by Minimum Duration (2+ days) Source: https://ohdsi.github.io/CohortConstructor/reference/requireDuration.html This example demonstrates how to use requireDuration to keep cohort entries that last for at least 2 days. It uses a range of c(2, Inf) to specify this minimum duration. The original cohort table 'cohort1' will be overwritten unless a new name is provided. ```r # \donttest{ library(CohortConstructor) cdm <- mockCohortConstructor() cdm$cohort1 |> requireDuration(daysInCohort = c(2, Inf)) # } ``` -------------------------------- ### Modify Cohort Table to Start Within a Date Range Source: https://ohdsi.github.io/CohortConstructor/reference/requireInDateRange.html Modifies the input cohort table to retain only records where the index date falls within the specified range. If the `name` argument is omitted, the original cohort table will be overwritten. This example demonstrates filtering to include records starting between '2010-01-01' and the end of the available data. ```r # modify same input cohort table to start between 2010 until end of data cdm$cohort1 <- cdm$cohort1 | requireInDateRange( indexDate = "cohort_start_date", dateRange = as.Date(c("2010-01-01", NA)) ) ``` -------------------------------- ### Mock CDM and Create Cohort Source: https://ohdsi.github.io/CohortConstructor/articles/a05_update_cohort_start_end.html Sets up a mock CDM database and creates a base cohort of females for demonstration purposes. Requires loading several R packages. ```R library(dplyr, warn.conflicts = FALSE) library(CohortConstructor) library(CohortCharacteristics) library(PatientProfiles) library(omock) library(clock) cdm <- mockCdmFromDataset(datasetName = "GiBleed", source = "duckdb") cdm$cohort <- demographicsCohort(cdm = cdm, name = "cohort", sex = "Female") ``` -------------------------------- ### Pad Cohort End Dates Source: https://ohdsi.github.io/CohortConstructor/index.html Extend the cohort exit dates up to a specified number of days after the start date, respecting the individual's observation period end date. This example pads the exit date by up to 180 days. ```r cdm$fractures <- cdm$fractures |> padCohortEnd(days = 180) ``` -------------------------------- ### Require Prior Record in Visit Occurrence Table Source: https://ohdsi.github.io/CohortConstructor/articles/a04_require_intersections.html Filters a cohort to include only individuals who have at least one prior record in the visit occurrence table before the cohort start date. This example uses the 'warfarin' cohort and requires a prior visit. ```r cdm$warfarin_visit <- cdm$warfarin |> requireTableIntersect(tableName = "visit_occurrence", indexDate = "cohort_start_date", window = c(-Inf, -1), name = "warfarin_visit") summary_attrition <- summariseCohortAttrition(cdm$warfarin_visit) plotCohortAttrition(summary_attrition) ``` -------------------------------- ### benchmarkCohortConstructor Source: https://ohdsi.github.io/CohortConstructor/reference/benchmarkCohortConstructor.html Runs a benchmark to compare the cohort instantiation time of CohortConstructor against CIRCE. It allows for selective benchmarking of different components. ```APIDOC ## benchmarkCohortConstructor ### Description Run benchmark of CohortConstructor cohort instantiation time compared to CIRCE from JSON. More information in the benchmarking vignette. ### Usage ```R benchmarkCohortConstructor( cdm, runCIRCE = TRUE, runCohortConstructorDefinition = TRUE, runCohortConstructorDomain = TRUE, dropCohorts = TRUE ) ``` ### Arguments * **cdm** (object) - A cdm reference. * **runCIRCE** (logical) - Whether to run cohorts from JSON definitions generated with Atlas. * **runCohortConstructorDefinition** (logical) - Whether to run the benchmark part where cohorts are created with CohortConstructor by definition (one by one, separately). * **runCohortConstructorDomain** (logical) - Whether to run the benchmark part where cohorts are created with CohortConstructor by domain (instantiating base cohort all together, as a set). * **dropCohorts** (logical) - Whether to drop cohorts created during benchmark. ``` -------------------------------- ### Pad Cohort Start Date Source: https://ohdsi.github.io/CohortConstructor/articles/a05_update_cohort_start_end.html Adds or subtracts days from the cohort start date. By default, corrects entries preceding observation start to the observation start. Set requireFullContribution to TRUE to drop such entries. ```r # Substract 50 days to cohort start cdm$cohort <- cdm$cohort |> padCohortStart(days = -50, collapse = FALSE) ``` -------------------------------- ### Configure SQL Logging Source: https://ohdsi.github.io/CohortConstructor/articles/a12_behind_the_scenes.html Sets up a directory to log all SQL statements executed by CohortConstructor. This is useful for debugging and understanding the generated SQL, especially when targeting specific database systems like duckdb. ```r dir_sql <- file.path(tempdir(), "sql_folder") dir.create(dir_sql) options("omopgenerics.log_sql_path" = dir_sql) ``` -------------------------------- ### Add days to cohort start date Source: https://ohdsi.github.io/CohortConstructor/reference/padCohortStart.html Adds a specified number of days to the cohort start date. Cohort entries will be dropped if the new start date is after the cohort end date or before the observation period start. Use the `name` argument to specify a new table name for the modified cohort. ```r library(CohortConstructor) cdm <- mockCohortConstructor() # add 10 days to each cohort entry cdm$cohort1 |> padCohortStart(days = 10) ``` -------------------------------- ### Create CDM Reference with Mock Data Source: https://ohdsi.github.io/CohortConstructor/articles/a01_building_base_cohorts.html Establishes a connection to a CDM database using mock data for testing and development. Ensure all required packages are loaded before execution. ```r library(omock) library(CodelistGenerator) library(PatientProfiles) library(CohortConstructor) library(dplyr) library(CDMConnector) library(duckdb) cdm <- mockCdmFromDataset(datasetName = "GiBleed", source = "duckdb") ``` -------------------------------- ### Update cohort start date to the first date from a set of column dates Source: https://ohdsi.github.io/CohortConstructor/reference/entryAtFirstDate.html Resets cohort start date based on a set of specified column dates. The first date that occurs is chosen. Use this when you need to align cohort start dates to the earliest of several potential event dates. ```r entryAtFirstDate( cohort, dateColumns, cohortId = NULL, returnReason = FALSE, keepDateColumns = TRUE, name = tableName(cohort), .softValidation = FALSE ) ``` ```r library(CohortConstructor) library(PatientProfiles) cdm <- mockCohortConstructor() cdm$cohort1 <- cdm$cohort1 | addTableIntersectDate( tableName = "drug_exposure", nameStyle = "prior_drug", order = "last", window = c(-Inf, 0) ) | addPriorObservation(priorObservationType = "date", name = "cohort1") cdm$cohort1 | entryAtFirstDate(dateColumns = c("prior_drug", "prior_observation")) ``` -------------------------------- ### Update cohort start and end dates Source: https://ohdsi.github.io/CohortConstructor/reference/index.html Functions to modify the start and end dates of cohort records, including setting them to specific events or padding them. ```APIDOC ## entryAtFirstDate() ### Description Update cohort start date to be the first date from of a set of column dates. ### Method N/A (R function) ### Endpoint N/A (R function) ### Parameters N/A (R function parameters not specified in source) ### Request Example N/A ### Response N/A ``` ```APIDOC ## entryAtLastDate() ### Description Set cohort start date to the last of a set of column dates. ### Method N/A (R function) ### Endpoint N/A (R function) ### Parameters N/A (R function parameters not specified in source) ### Request Example N/A ### Response N/A ``` ```APIDOC ## exitAtDeath() ### Description Set cohort end date to death date. ### Method N/A (R function) ### Endpoint N/A (R function) ### Parameters N/A (R function parameters not specified in source) ### Request Example N/A ### Response N/A ``` ```APIDOC ## exitAtFirstDate() ### Description Set cohort end date to the first of a set of column dates. ### Method N/A (R function) ### Endpoint N/A (R function) ### Parameters N/A (R function parameters not specified in source) ### Request Example N/A ### Response N/A ``` ```APIDOC ## exitAtLastDate() ### Description Set cohort end date to the last of a set of column dates. ### Method N/A (R function) ### Endpoint N/A (R function) ### Parameters N/A (R function parameters not specified in source) ### Request Example N/A ### Response N/A ``` ```APIDOC ## exitAtObservationEnd() ### Description Set cohort end date to end of observation. ### Method N/A (R function) ### Endpoint N/A (R function) ### Parameters N/A (R function parameters not specified in source) ### Request Example N/A ### Response N/A ``` ```APIDOC ## padCohortDate() ### Description Set cohort start or cohort end. ### Method N/A (R function) ### Endpoint N/A (R function) ### Parameters N/A (R function parameters not specified in source) ### Request Example N/A ### Response N/A ``` ```APIDOC ## padCohortEnd() ### Description Add days to cohort end. ### Method N/A (R function) ### Endpoint N/A (R function) ### Parameters N/A (R function parameters not specified in source) ### Request Example N/A ### Response N/A ``` ```APIDOC ## padCohortStart() ### Description Add days to cohort start. ### Method N/A (R function) ### Endpoint N/A (R function) ### Parameters N/A (R function parameters not specified in source) ### Request Example N/A ### Response N/A ``` ```APIDOC ## trimDemographics() ### Description Trim cohort on patient demographics. ### Method N/A (R function) ### Endpoint N/A (R function) ### Parameters N/A (R function parameters not specified in source) ### Request Example N/A ### Response N/A ``` ```APIDOC ## trimDuration() ### Description Trim cohort dates to be within a certain interval of days. ### Method N/A (R function) ### Endpoint N/A (R function) ### Parameters N/A (R function parameters not specified in source) ### Request Example N/A ### Response N/A ``` ```APIDOC ## trimToDateRange() ### Description Trim cohort dates to be within a date range. ### Method N/A (R function) ### Endpoint N/A (R function) ### Parameters N/A (R function parameters not specified in source) ### Request Example N/A ### Response N/A ``` -------------------------------- ### Inspect Initial Cohort Settings Source: https://ohdsi.github.io/CohortConstructor/index.html View the initial settings, counts, and attrition of defined cohorts before applying any modifications. This provides a baseline for subsequent operations. ```r settings(cdm$fractures) |> glimpse() cohortCount(cdm$fractures) |> glimpse() attrition(cdm$fractures) |> glimpse() ``` -------------------------------- ### Run CohortConstructor Benchmark Source: https://ohdsi.github.io/CohortConstructor/articles/a11_benchmark.html Executes the CohortConstructor benchmark function, focusing on domain-based cohort construction. The results capture the time taken for different tasks. ```r benchmark_results <- benchmarkCohortConstructor( cdm, runCIRCE = FALSE, runCohortConstructorDefinition = FALSE, runCohortConstructorDomain = TRUE ) #> cc_set_no_strata: 96.99 sec elapsed #> cc_set_strata: 1.399 sec elapsed ``` -------------------------------- ### Benchmark CohortConstructor Package Source: https://ohdsi.github.io/CohortConstructor/reference/benchmarkCohortConstructor.html Use this function to benchmark the cohort instantiation time of the CohortConstructor package compared to CIRCE. It allows control over which benchmarking parts to run and whether to drop created cohorts. ```r benchmarkCohortConstructor( cdm, runCIRCE = TRUE, runCohortConstructorDefinition = TRUE, runCohortConstructorDomain = TRUE, dropCohorts = TRUE ) ``` -------------------------------- ### Require Cohort Start Date in Date Range Source: https://ohdsi.github.io/CohortConstructor/index.html Filter the cohort to include only individuals whose cohort start date falls within a specified date range. This is useful for time-based cohort definitions. ```r cdm$fractures <- cdm$fractures |> requireInDateRange(dateRange = as.Date(c("2000-01-01", "2020-01-01"))) ``` -------------------------------- ### Compute Date IDs for Overlap Calculation Source: https://ohdsi.github.io/CohortConstructor/articles/a12_behind_the_scenes.html Prepares data for overlap calculations by assigning date IDs to cohort start and end dates. This involves a UNION ALL to stack start and end dates for processing. ```sql SELECT *, -1.0 AS date_id FROM ( SELECT cohort_definition_id, subject_id, cohort_start_date AS date FROM results.test_drugs ) AS q01 UNION ALL SELECT *, 1.0 AS date_id FROM ( SELECT cohort_definition_id, subject_id, cohort_end_date AS date FROM results.test_drugs ) AS q01 ``` -------------------------------- ### Log SQL Query: Detect Overlapping Cohort Dates Source: https://ohdsi.github.io/CohortConstructor/articles/a12_behind_the_scenes.html This snippet logs a query to detect overlapping cohort start and end dates for the same subject and cohort definition. It uses the LEAD window function to find the next cohort start date. ```sql SELECT * FROM ( SELECT subject_id, CASE WHEN (cohort_end_date >= next_cohort_start_date) THEN 1 WHEN NOT (cohort_end_date >= next_cohort_start_date) THEN 0 END AS overlap FROM ( SELECT *, LEAD(cohort_start_date, 1, NULL) OVER (PARTITION BY cohort_definition_id, subject_id ORDER BY cohort_start_date) AS next_cohort_start_date FROM results.test_drugs ) AS q01 ) AS q01 WHERE (overlap = 1) ``` -------------------------------- ### Access CohortConstructor Benchmarking Data Source: https://ohdsi.github.io/CohortConstructor/reference/benchmarkData.html Use this command to retrieve the benchmarking results. The data is provided as a list. ```r benchmarkData ``` -------------------------------- ### Create Mock CDM Data Source: https://ohdsi.github.io/CohortConstructor/articles/a09_combine_cohorts.html Generate a mock Common Data Model (CDM) environment using the omock package for demonstration purposes. ```r cdm <- mockCdmFromDataset(datasetName = "GiBleed", source = "duckdb") ``` -------------------------------- ### Configure and Log SQL Execution Plans Source: https://ohdsi.github.io/CohortConstructor/articles/a12_behind_the_scenes.html This R code configures the OHDSI CohortConstructor to log SQL execution plans to a specified directory. It then processes and prints these plans. ```r dir_explain <- file.path(tempdir(), "explain_folder") dir.create(dir_explain) options("omopgenerics.log_sql_explain_path" = dir_explain) cdm$drugs <- cdm$drugs |> requireIsFirstEntry() files <- list.files(dir_explain, full.names = TRUE) file_names <- list.files(dir_explain, full.names = FALSE) for(i in seq_along(files)) { cat(paste0("### ", file_names[i], "\n\n")) sql_with_quotes <- paste0('"', paste(readLines(files[i]), collapse = '\n'), '"') cat(sql_with_quotes, "\n```\n\n") } ``` -------------------------------- ### Package benchmark Source: https://ohdsi.github.io/CohortConstructor/reference/index.html Functions to run benchmarks for the CohortConstructor package and access benchmarking results. ```APIDOC ## benchmarkCohortConstructor() ### Description Run benchmark of CohortConstructor package. ### Method N/A (R function) ### Endpoint N/A (R function) ### Parameters N/A (R function parameters not specified in source) ### Request Example N/A ### Response N/A ``` ```APIDOC ## benchmarkData ### Description Benchmarking results. ### Method N/A (R object) ### Endpoint N/A (R object) ### Parameters N/A (R object parameters not specified in source) ### Request Example N/A ### Response N/A ``` -------------------------------- ### Trim Cohort Duration to a Specific Interval Source: https://ohdsi.github.io/CohortConstructor/reference/trimDuration.html Resets cohort start and end dates, keeping only records that span a specified number of days. Use this to filter cohorts by their duration relative to their start date. The `name` argument can be used to specify a new table name to avoid overwriting the original. ```r library(CohortConstructor) cdm <- mockCohortConstructor() cdm$cohort1 %>% requireDuration(daysInCohort = c(2, Inf)) ``` -------------------------------- ### trimDuration Source: https://ohdsi.github.io/CohortConstructor/reference/trimDuration.html Resets the cohort start and end date, keeping only those which include the specified amount of days. ```APIDOC ## trimDuration() ### Description Resets the cohort start and end date, keeping only those which include the specified amount of days. ### Usage ```R trimDuration(cohort, daysInCohort, cohortId = NULL, name = tableName(cohort)) ``` ### Arguments * **cohort** (table) - A cohort table in a cdm reference. * **daysInCohort** (numeric) - Number of days cohort relative to current cohort start dates. Cohort entries will be trimmed to these dates. Note, cohort entry and exit on the same day counts as one day in the cohort. Set lower bound to 1 if keeping cohort start to the same as current cohort start. * **cohortId** (numeric, optional) - Vector identifying which cohorts to modify (cohort_definition_id or cohort_name). If NULL, all cohorts will be used; otherwise, only the specified cohorts will be modified, and the rest will remain unchanged. * **name** (string, optional) - Name of the new cohort table created in the cdm object. ### Value The cohort table with any cohort entries that last less or more than the required duration dropped. ### Examples ```R # \donttest{ library(CohortConstructor) cdm <- mockCohortConstructor() cdm$cohort1 |> requireDuration(daysInCohort = c(2, Inf)) # } ``` -------------------------------- ### Inspect Cohort Data Source: https://ohdsi.github.io/CohortConstructor/articles/a01_building_base_cohorts.html Use `glimpse()` to view the structure and a sample of the created cohort data. This helps in verifying the cohort creation process. ```r cdm$celecoxib | glimpse() ``` -------------------------------- ### collapseCohorts Source: https://ohdsi.github.io/CohortConstructor/reference/collapseCohorts.html Concatenates cohort records, allowing for some number of days between one finishing and the next starting. ```APIDOC ## collapseCohorts() ### Description Concatenates cohort records, allowing for some number of days between one finishing and the next starting. ### Usage ```R collapseCohorts( cohort, cohortId = NULL, gap = 0, name = tableName(cohort), .softValidation = FALSE ) ``` ### Arguments * **cohort** (A cohort table in a cdm reference.) - Required * **cohortId** (Vector identifying which cohorts to modify (cohort_definition_id or cohort_name). If NULL, all cohorts will be used; otherwise, only the specified cohorts will be modified, and the rest will remain unchanged.) - Optional * **gap** (Number of days between two subsequent cohort entries to be merged in a single cohort record.) - Optional, Default: 0 * **name** (Name of the new cohort table created in the cdm object.) - Optional, Default: tableName(cohort) * **.softValidation** (Whether to perform a soft validation of consistency. If set to FALSE four additional checks will be performed: 1) a check that cohort end date is not before cohort start date, 2) a check that there are no missing values in required columns, 3) a check that cohort duration is all within observation period, and 4) that there are no overlapping cohort entries) - Optional, Default: FALSE ### Value A cohort table ### Examples ```R # \donttest{ library(CohortConstructor) cdm <- mockCohortConstructor() # collapse just cohort 1, with a gap of 7 days cdm$cohort1 <- cdm$cohort1 |> collapseCohorts(cohortId = 1, gap = 7) # collapse both cohorts with a gap of 1 year, and change table name cdm$collapsed_cohort <- cdm$cohort1 |> collapseCohorts(gap = 365, name = "collapsed_cohort") # } ``` ``` -------------------------------- ### View Cohort Settings Source: https://ohdsi.github.io/CohortConstructor/reference/measurementCohort.html Displays the settings and metadata for the created cohort, including definition ID, name, CDM version, and vocabulary version. This is useful for verifying cohort construction parameters. ```r cdm$cohort2 |> settings() ``` -------------------------------- ### Load required R packages Source: https://ohdsi.github.io/CohortConstructor/articles/a04_require_intersections.html Loads the necessary libraries for cohort construction and data manipulation. ```r library(omock) library(dplyr) library(CodelistGenerator) library(CohortConstructor) library(CohortCharacteristics) library(visOmopResults) library(ggplot2) ``` -------------------------------- ### Inspect Unioned Cohort Settings and Counts Source: https://ohdsi.github.io/CohortConstructor/index.html Verify the settings and counts after creating a union cohort. This confirms the new cohort has been added and its initial statistics are recorded. ```r settings(cdm$fractures) cohortCount(cdm$fractures) ```