r – Matching only unique participants

I am having trouble matching my historical cohort to a study cohort in R studio.

Objective: Get a match to every patient in my study cohort using the historical cohort.

I want each patient in the historical cohort to be matched only once maximum to a study patient.
However, a patient can be present in the historical dataset several times, because my dataset of historical patients includes a row for every visit of every patient.
I want every visit of the same patient to be a possible match but would like to match each historical patient just once.
If a historical patient is matched, I do not want another visit of the same patient to be matched.

Details of the historical dataset:

  • I have a variable with a number for the unique visit.
  • I have a variable with the patient ID.

So far, I have not succeeded. Could you help me with the code?

I have tried this code below, but end up with one historical patient being matched several times, on different time points.

My code:

# Load dplyr and MatchIt
library(dplyr)
library(MatchIt)

# Example data for study_cohort dataset
study_cohort <- data.frame(
  ID = 1:20,
  Age = sample(25:65, 20, replace = TRUE),
  Meds = sample(1:5, 20, replace = TRUE)
)

# Example data for historical_cohort dataset
historical_cohort <- data.frame(
  VisitID = 1:80,
  ID = sprintf("%05d", 101:120)[sample(1:20, 80, replace = TRUE)],  # Willekeurige selectie van historische IDs
  Age = sample(25:65, 80, replace = TRUE),
  Meds = sample(1:5, 80, replace = TRUE)
)

# Convert to have the same in both datasets 
study_cohort$ID <- as.character(study_cohort$ID)

# Combine the two datasets 
study_cohort$group <- 1 # study 
historical_cohort$group <- 0 # historical

combined_data <- bind_rows(study_cohort, historical_cohort)

# Match
match_formula <- as.formula("group ~ Age + Meds")

matched <- matchit(match_formula, data = combined_data, method = "nearest", ratio = 1, replace =  FALSE)

matched_data <- match.data(matched)

# Split dataset
matched_study <- matched_data %>%
  filter(group == "1") # study

matched_historical <- matched_data %>%
  filter(group == "0") # historical

# Inspect data of matched_historical
View(matched_historical)
# When I inspect this data I see that several patients are used multiple times, but at different visits, which is not my intention

Furthermore, I have tried to only select one visit per patient, but then only the first visit of each historical patient can be a potential match, even though I want all visits to be potential matches.

Read more here: Source link