Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
1.6 kB
3
Indexable
Never
# Duration Medication 
calculate_duration_medication <- function(dat, med_var) {
  # Construct variable names
  start_name <- paste0("start_", med_var)
  stop_name <- paste0("stop_", med_var)
  followup_name <- paste0("last_followup_", med_var)
  q10_name <- paste0("q10_", med_var)
  
  # Identify the first time each patient initiated the medication
  initiate <- dat[get(med_var) == 1, .(start = min(t1)), by = .(id)]
  
  # Extend the dataset with the initiation time and filter rows after initiation
  after_initiate = merge(dat, initiate, by="id")[t1 >= start]
  
  # Identify the first time each patient stopped the medication after initiation
  stop_med = after_initiate[get(med_var) == 0, .(stop = min(t1)), by = .(id, start)][, .(id, stop)]
  
  # Identify the last follow-up time for each patient still on the medication after initiation
  followup_med = after_initiate[get(med_var) == 1, .(last_followup = max(t2)), by = .(id, start)][, .(id, last_followup)]
  
  # Merge the data
  q10_med = merge(initiate, stop_med, by = "id", all = TRUE)
  q10_med = merge(q10_med, followup_med, by = "id", all = TRUE)
  
  # Calculate the duration of medication use
  q10_med[, duration := ifelse(is.na(stop), last_followup, stop) - start]
  
  # Generate summary
  summary_data <- summary(q10_med$duration)
  
  # Convert the summary to a data frame for better display in datatable
  summary_df <- data.frame(
    Statistic = names(summary_data),
    Days = round(as.numeric(summary_data),2)
  )
  
  # Display the data frame as a datatable
  datatable(summary_df)
}

calculate_duration_medication(dat, "ace")