Text highlighted like this is provisional: it depends on a decision the analysis plan has not yet made. To comment on any part of this page, highlight the text and use the 💬 Comment button.
Overview
The code in this script uses the cohort of kidney transplant patients with and without cryptococcosis developed in the R/create_cohort.R and executes 1:n matching based on a custom-written greedy algorithm
Characteristics of the matching algorithm:
Matching without replacement:each patient without cryptococcosis serves as a control to at most one case, which keeps the later analysis simpler1.
Risk-set sampling (incidence density sampling): if a case develops cryptococcosis 243 days after their most recent kidney transplant, potential controls are chosen on their covariate values at exactly 243 days after their own most recent transplant2.
Greedy matching: each case’s controls are chosen in turn, and earlier choices are not revisited3. Cases are taken in order of how few potential controls they have, a choice made in this code; the order of greedy matching has at most a modest effect on estimates3.
Mix of exact matching and caliper matching
Exact matching on the following:
Cirrhosis
HIV
Diabetes
Caliper matching on the following:
Age (within 10 years on the index date, calculated exactly)
Index date of case and controls (within 3 years of each other)
Preferential matching on the following:
Number of transplants prior to index date
Decision pending: whether a person may serve as a control in more than one risk set (D4).
Current code: potential controls are limited to patients never diagnosed with cryptococcosis, so people diagnosed later cannot serve as controls before their diagnosis (#7). Other differences from the plan, including the order in which cases are matched, are listed under Cases and controls.
The code sections below are imported directly from that script when this page is rendered.
Prepare cohort for matching
The following code prepares the cohort for matching by creating a list object unmatched_patients, keeping only the initial row for each case as only the covariates at the time of cryptococcus are necessary for matching.
Click to show/hide R Code
unmatched_patients<-list()unmatched_patients[["Case"]]<-prematching_cohort%>%filter(cryptococcus_case=="Case")unmatched_patients[["Control"]]<-prematching_cohort%>%filter(cryptococcus_case=="Potential control")unmatched_patients[["Case"]]<-unmatched_patients[["Case"]]%>%group_by(USRDS_ID)%>%slice(1)%>%ungroup()#For exploration--perhaps can delete in future?Case<-unmatched_patients[["Case"]]Control<-unmatched_patients[["Control"]]
Counting the potential number of matched controls for each case
This step uses the calculate_number_potential_matches() function defined in the R/functions.R to add a column to the cases data set, then sorts the cases so that those with the lowest number of potential matches are matched first.
(Note the following code took ~2 hours to execute on a laptop given the size of the dataset.)
#Add number of potential control matches to Case dfunmatched_patients[["Case"]] <- unmatched_patients[["Case"]] %>%mutate(num_potential_controls =pmap_int(list(USRDS_ID, BORN,cirrhosis, CMV, HIV, diabetes, cryptococcus_dx_date, tstart),function(USRDS_ID, BORN, cirrhosis, CMV, HIV, diabetes, matching_date, tstart) {calculate_number_potential_matches( unmatched_patients[["Control"]], USRDS_ID, BORN, cirrhosis, CMV, HIV, diabetes, matching_date, tstart ) } ) )#Sort by number of potential matches so that most difficult to match cases are matched first#Set the index_date for cases to be the date of cryptococcus dxunmatched_patients[["Case"]] <- unmatched_patients[["Case"]] %>%arrange(num_potential_controls)%>%mutate(index_date_match=cryptococcus_dx_date)#Can be deletedunmatched_patients_backup<-unmatched_patientsunmatched_patients<-unmatched_patients_backup
Create a matched data set
The following code executes the match, creating a matched dataframe suitable for use in subsequent analysis.
Click to show/hide R Code
#Time to set up the matching loop#Initial the loop controlcontinue<-TRUEi<-0set.seed(12345)#Initialize the object where the matched cases and controls will be storedmatched_patients<-list()matched_patients[["Case"]]<-unmatched_patients[["Case"]][0, ]%>%mutate(matched_control_indices =list())matched_patients[["Control"]] <- unmatched_patients[["Control"]][0, ] %>%mutate(index_date_match =as.Date(character()))#Perform the matchwhile (continue==TRUE){ i<-i+1print(i)#Select matches from controls eligible_controls <-unmatched_patients[["Control"]]%>%filter(cirrhosis==unmatched_patients$Case$cirrhosis[[1]])%>%#filter(CMV==unmatched_patients$Case$CMV[[1]])%>%filter(HIV==unmatched_patients$Case$HIV[[1]])%>%filter(diabetes==unmatched_patients$Case$diabetes[[1]])%>%#Risk set matchingfilter(tstart<=unmatched_patients$Case$tstart[[1]])%>%filter(tstop>unmatched_patients$Case$tstart[[1]])%>%#Calculate date for age calculations/etc.mutate(.baseline_control_date=unmatched_patients$Case$tstart[[1]] + most_recent_transplant_date)%>%#Make sure case and control are sampled within 3 years of each otherfilter(abs(time_length(interval(.baseline_control_date, unmatched_patients$Case$cryptococcus_dx_date[[1]]), "years")) <=3)%>%#filter(cohort_start_date<=unmatched_patients$Case$cryptococcus_dx_date[[1]])%>%#filter(cohort_stop_date>unmatched_patients$Case$cryptococcus_dx_date[[1]])%>%#Age>=18 on index datefilter(time_length(interval(BORN, .baseline_control_date), "years") >=18)%>%#Age difference under 10 years, calculated at sampling datefilter(abs(time_length(interval(BORN,.baseline_control_date), "years")-time_length(interval(unmatched_patients$Case$BORN[[1]], unmatched_patients$Case$cryptococcus_dx_date[[1]]), "years")) <=10)%>%verify_medicare_primary(index_date =".baseline_control_date", medicare_coverage_df = medicare_history, coverage_start_variable ="medicare_coverage_start_date",coverage_end_variable ="medicare_coverage_end_date",cache=TRUE)%>%filter(medicare_primary_TF==TRUE)%>%#Move matches for cumulative number of transplants to the top#Note: this step could be used for propensity score matching on various variables#Consider minimizing date difference and age difference as wellarrange(desc(cumulative_transplant_total==unmatched_patients$Case$cumulative_transplant_total[[1]]))#Number of controls is minimum of global constant number_controls_per_case and number of distinct USRDS_IDs k <-min(number_controls_per_case, nrow(distinct(eligible_controls, USRDS_ID)))#Initialize sampled_controls df sampled_controls<-eligible_controls[0, ]#Loop to select controls one at a time to ensure same patient is not sampled multiple times while (k>0) { sampled_controls <-bind_rows( sampled_controls, eligible_controls %>%slice_head(n =1)) eligible_controls<-eligible_controls%>%filter(!(USRDS_ID %in% sampled_controls$USRDS_ID )) k<-min(k-1, nrow(distinct(eligible_controls, USRDS_ID))) } sampled_controls<-sampled_controls%>%mutate(index_date_match = .baseline_control_date)%>%select(-.baseline_control_date)#Add case to matched DF matched_patients[["Case"]]<-unmatched_patients$Case[1,]%>%mutate(matched_control_indices=list(sampled_controls$USRDS_ID))%>%bind_rows(matched_patients[["Case"]])#Add controls to control DF matched_patients[["Control"]]<-matched_patients[["Control"]]%>%bind_rows(sampled_controls)#Remove controls unmatched_patients[["Control"]]<-unmatched_patients[["Control"]]%>%filter(!(USRDS_ID %in% sampled_controls$USRDS_ID ))#Remove cases unmatched_patients[["Case"]]<-unmatched_patients[["Case"]]%>%slice(-1)if (nrow(unmatched_patients[["Case"]])==0){ continue<-FALSE } if (i==10000){ continue<-FALSE }}post_match_results<-matched_patients%>%bind_rows(.id ="patient_type")
The modeling script uses the above matched dataframe for the actual cost analysis.
References
1.
Stuart EA. Matching methods for causal inference: A review and a look forward. Stat Sci. 2010;25(1):1-21. doi:10.1214/09-STS313
2.
Richardson DB. An incidence density sampling program for nested case-control analyses. Occup Environ Med. 2004;61(12):e59. doi:10.1136/oem.2004.014472
3.
Austin PC. A comparison of 12 algorithms for matching on the propensity score. Stat Med. 2014;33(6):1057-1069. doi:10.1002/sim.6004
---title: "Execute matching"format: html---## OverviewThe code in this script uses the cohort of kidney transplant patients with and without cryptococcosis developed in the [`R/create_cohort.R`](create_cohort.qmd)and executes 1:n matching based on a custom-written greedy algorithmCharacteristics of the matching algorithm:- **Matching without replacement:** [each patient without cryptococcosis serves as a control to at most one case]{.pending}, which keeps the later analysis simpler [@stuart2010matching].- **Risk-set sampling (incidence density sampling):** if a case develops cryptococcosis 243 days after their most recent kidney transplant, potential controls are chosen on their covariate values at exactly 243 days after their own most recent transplant [@richardson2004incidence].- **Greedy matching:** each case's controls are chosen in turn, and earlier choices are not revisited [@austin2014algorithms]. Cases are taken in order of how few potential controls they have, a choice made in this code; the order of greedy matching has at most a modest effect on estimates [@austin2014algorithms].- **Mix of exact matching and caliper matching** - Exact matching on the following: - Cirrhosis - HIV - Diabetes - Caliper matching on the following: - Age (within 10 years on the index date, calculated exactly) - Index date of case and controls (within 3 years of each other) - Preferential matching on the following: - Number of transplants prior to index date **Decision pending:** whether a person may serve as a control in more than one risk set ([D4](analysis-plan.qmd#13-open-decisions)).**Current code:** potential controls are limited to patients never diagnosed with cryptococcosis, so people diagnosed later cannot serve as controls before their diagnosis ([#7](https://github.com/VagishHemmige/Cryptococcus-cost-analysis/issues/7)). Other differences from the plan, including the order in which cases are matched, are listed under [Cases and controls](study_cases_controls.qmd#what-cases-and-controls-are-matched-on).::: Rcode### Source codeThe full R script is available at:- [`R/execute_matching.R`](https://github.com/VagishHemmige/Cryptococcus-cost-analysis/blob/master/R/execute_matching.R)This R script file is itself reliant on the following helper files:- [`R/setup.R`](https://github.com/VagishHemmige/Cryptococcus-cost-analysis/blob/master/R/setup.R)- [`R/functions.R`](https://github.com/VagishHemmige/Cryptococcus-cost-analysis/blob/master/R/functions.R)The code sections below are imported directly from that script when this page is rendered.:::```{r}#| include: false#| cache: falseknitr::read_chunk("../R/execute_matching.R")```## Prepare cohort for matchingThe following code prepares the cohort for matching by creating a list object `unmatched_patients`, keeping only the initial row for each case as onlythe covariates at the time of cryptococcus are necessary for matching.```{r}#| label: prepare-cohort#| eval: false```## Counting the potential number of matched controls for each caseThis step uses the `calculate_number_potential_matches()` function defined in the [`R/functions.R`](functions.qmd) to add a column to the cases data set, thensorts the cases so that those with the lowest number of potential matches are matched first.(Note the following code took ~2 hours to execute on a laptop given the size of the dataset.)**Functions used:** [`calculate_number_potential_matches()`](functions.qmd#calculating-the-number-of-potential-matches).```{r}#| label: count-potential-matches#| eval: false```## Create a matched data setThe following code executes the match, creating a matched dataframe suitable for use in subsequent analysis.```{r}#| label: matching-loop#| eval: false```The [modeling](modeling.qmd) script uses the above matched dataframe for the actual cost analysis.## References::: {#refs}:::