terlipressin <- read_xlsx("/Users/to909/Desktop/Terlipressin/final_master_0508.xlsx")



terlipressin_numeric <- terlipressin  # make a copy

for (col in names(terlipressin_numeric)) {
  # Suppress warnings like "NAs introduced by coercion"
  converted <- suppressWarnings(as.numeric(terlipressin_numeric[[col]]))
  
  # If at least one value successfully converted (not NA), keep it
  if (any(!is.na(converted))) {
    terlipressin_numeric[[col]] <- converted
  }
}




terlipressin_numeric <- terlipressin_numeric %>% mutate(group="terli",death_discharge=ifelse(disposition==5,1,0))


terlipressin_numeric <- terlipressin_numeric %>% rename(terli_resfailuretype_day2=terli_resfailuretype_day1_day2)









terlipressin_numeric <- terlipressin_numeric %>% select(-any_of(c("fena"))) %>% 
  rename(
    age_admission = age, 
    sex = sex_male,
    White = race, 
    hispanic_race = hispanic,
    loop_diuretic = diuretics_preadmission,
    aldosterone_antagonist = potsp_diuretic_preadmission,
    lactulose = lactulose_preadmission,
    rifaximin = rifaximin_preadmission,
    prophylactic_antibiotic = sbp_ppx_preadmission,
    nsaids = nsaid_preadmission,
    beta_blockers = nsbb_preadmission,
    albumin_amount_admission = totalalbumin_before_terli,# changed 1129
    diabetes = dm_medical_hx,
    cad = cad_medical_hx,
    htn = htn_medical_hx,
    etiology_cirrhosis = cirrhosis_etiology,
    ascites_admission = ascites_previous_comp,
    encephalopathy_admission = he_previous_comp,
    gi_bleed_admission = gibleed_hosp,
    peritonitis_admission = sbp_previous_comp,
    hcc_admission = hcc_previous_comp,
    tips_admission = tips_previous_comp,
    na_admit = na_terli_day0,
    k_admit = k_terli_day0,
    cl_admit = chloride_terli_day0,
    co2_admit = bicarb_terli_day0,
    bun_admit = bun_terli_day0,
    urine_creatinine = ua_cr_value_hrs,
    fena = fena_hrs,
    he_grade_admission = hegrade_admit,
    baseline_creatinine=baseline_scr,
    CLIF_C_Score=clif_c_score,
    aclf_grade=aclf_grade,
    liver_transplant_listed = listed_transplant,
    icu_admission = icu_admit,
    liver_transplant = transplant_lt_status,
    peak_creatinine =peakhospit_scr,
    AKI_responders=hrs_responders,
    death_in_90days_status = time_to_death_status, # checked 1129
    los = days_to_discharge,
    intubated=mv_use,# checked 1129
    discharge_disposition = disposition,
    creatinine_admission = scr_admit,
    time_90days=time_to_death_90days_cmp,
    status_90days=time_to_death_status_90days_cmp,
    MELD_baseline = admit_meld,# checked 1129
    MELD_Na_baseline = admit_meld_na,# checked 1129
    palliative_care = pall_consult# checked 1129
    # sbp_admission = aki_sbp,
    # dbp_admission = aki_dbp,
    # rrt = rrt_aki,
    # rrt_hemodialysis = rrt_modality,
    # alt_admit = alt_terli_day0,
    # tb_admit = bili_terli_day0,
    # alb_admit = albumin_admit,
    # inr_admit = inr_admit,
    # wbc_admit = wbc_terli_day0,
    # plt_admit = plt_terli_day0,
    # urine_sodium = ua_na_value_hrs,
    # intubated = mv_aki,
    # liver_transplant_listed = ltlisting_terli_day0,
    # peak_creatinine = scr_aki,
    # pressor = ne_before_terli,
    # kidney_transplant = slkt_during_hospital,
    
    # code_status = code_status,
    # MELD_baseline = admit_meld,
    # MELD_Na_baseline = admit_meld_na,
    # MAP = map_terli_day0_time0,
    # Alcoholic_hepatitis = etoh_hepatitis,
    # Transplant_evalutation = lt_eval,
    # Akin = akin,
    # death_discharge = disposition,
    # baseline_creatinine = baseline_scr,
    
    # death_in_90days_time = dc_days_to_death
  )  %>%
  
  mutate(
    # sex_male==1 -> sex==2 (male)
    sex = if_else(sex == 1, 1, 2), # updated 1129
    
    # race / ethnicity
    White = if_else(White == 1, 1, 0),
    hispanic_race = if_else(hispanic_race == 1, 1, 0),
    
    # medication use
    Loop_diuretic = if_else(loop_diuretic == 1, 1, 0),
    aldosterone_antagonist = if_else(aldosterone_antagonist == 1, 1, 0),
    lactulose = if_else(lactulose == 1, 1, 0),
    rifaximin = if_else(rifaximin == 1, 1, 0),
    prophylactic_antibiotic = if_else(prophylactic_antibiotic == 0, 0, 1),
    nsaids = if_else(nsaids == 1, 1, 0),
    beta_blockers = if_else(beta_blockers == 1, 1, 0),
    # albumin_given_prior = if_else(albumin_given_prior == 1, 1, 0),
    
    
    #rrt 
    rrt=ifelse(rrt==2,0,rrt),
    
    # comorbidities
    diabetes = if_else(diabetes == 1, 1, 0),
    cad = if_else(cad == 1, 1, 0),
    htn = if_else(htn == 1, 1, 0),
    
    # cirrhosis etiology mapping (reverse of your previous)

     etiology_cirrhosis = case_when(
      etiology_cirrhosis == 1 ~ 1,
      etiology_cirrhosis == 3 ~ 2,
      etiology_cirrhosis == 2 ~ 3,
      etiology_cirrhosis %in% c(4,5) ~ 4,
      etiology_cirrhosis == 6 ~ 5,
      TRUE ~ NA_real_
    ),  # changed 1129
    
    # complications
    ascites_admission = if_else(ascites_admission == 1, 1, 0),
    encephalopathy_admission = if_else(encephalopathy_admission == 1, 1, 0),
    gi_bleed_admission = if_else(gi_bleed_admission == 1, 1, 0),
    peritonitis_admission = if_else(peritonitis_admission == 1, 1, 0),
    hcc_admission = if_else(hcc_admission == 1, 1, 0),
    tips_admission = if_else(tips_admission == 1, 1, 0),
    
    # hepatic encephalopathy grade: new(0–4) → old(1–5)
    he_grade_admission = case_when(
      he_grade_admission == 0 ~ 1,
      he_grade_admission == 1 ~ 2,
      he_grade_admission == 2 ~ 3,
      he_grade_admission == 3 ~ 4,
      he_grade_admission == 4 ~ 5,
      TRUE ~ NA_real_
    ),
    liver_transplant=ifelse(liver_transplant==1 |liver_transplant==2,1,0),
    
     discharge_disposition = case_when(
      discharge_disposition == 5 ~ 1,
      discharge_disposition == 1 ~ 2,
      discharge_disposition == 2 ~ 3,
      discharge_disposition == 3 ~ 3,
      discharge_disposition == 4 ~ 4,
      TRUE ~ NA_real_
    ),
    AKI_responders=case_when(AKI_responders == 2 ~ "complete response",
                             AKI_responders == 1 ~ "partial response",
                             AKI_responders == 0 ~ "no response")
  )







create_first_nonzero_value <- function(data, original_variable, new_variable) {
  
  # Build the expected column names
  day_vars <- paste0(original_variable, "_day", 1:13)
  
  # Keep only those that exist in the dataset
  valid_day_vars <- day_vars[day_vars %in% names(data)]
  
  # Apply logic and keep only subjectid + new_variable
  data %>%
    rowwise() %>%
    mutate(
      !!sym(new_variable) := {
        values <- c_across(all_of(valid_day_vars))
        first_valid <- values[!is.na(values) & values != 0]
        if (length(first_valid) > 0) first_valid[1] else NA
      }
    ) %>%
    ungroup() %>%
    select(subjectid, all_of(new_variable))  # keep subjectid + new var
}

# respiratory_failure <- create_first_nonzero_value(
#   data = terlipressin_numeric,
#   original_variable = "terli_resfailuretype",
#   new_variable = "respiratory_failure"
# ) 
# 
# 
# albumin_given_admission <- create_first_nonzero_value(
#   data = terlipressin_numeric,
#   original_variable = "albumin_terli",
#   new_variable = "albumin_given_admission"
# )
# 
# 
# terlipressin_numeric <-terlipressin_numeric %>%  merge(respiratory_failure,by="subjectid",all.x = T)
# terlipressin_numeric <-terlipressin_numeric %>%  merge(albumin_given_admission,by="subjectid",all.x = T)



var1 <- c("group",
  "age_admission","sex","White","hispanic_race","loop_diuretic",
  "aldosterone_antagonist","lactulose","rifaximin","prophylactic_antibiotic",
  "nsaids","beta_blockers","albumin_amount_admission",
  "diabetes","cad","htn","etiology_cirrhosis",
  "ascites_admission","encephalopathy_admission","gi_bleed_admission",
  "peritonitis_admission","hcc_admission","tips_admission","na_admit",
  "k_admit","cl_admit","co2_admit","bun_admit","urine_creatinine","fena",
  "he_grade_admission","baseline_creatinine","CLIF_C_Score","aclf_grade",
  "liver_transplant_listed","icu_admission","liver_transplant",
  "peak_creatinine","AKI_responders",
  "creatinine_admission",
  "death_in_90days_status","los","discharge_disposition",
   "palliative_care","intubated","MELD_baseline",
   "MELD_Na_baseline","time_90days","status_90days","prophylactic_antibiotic","beta_blockers",
  "k_admit","cl_admit"

)




# 
# var1_old <- c(
#   "subjectid",
#   "age_admission",
#   "sex",
#   "White",
#   "hispanic_race",
#   "loop_diuretic",
#   "aldosterone_antagonist",
#   "lactulose",
#   "rifaximin",
#   "prophylactic_antibiotic",
#   "nsaids",
#   "beta_blockers",
#   "albumin_amount_admission",
#   "albumin_given_prior",
#   "albumin_amount_prior",
#   "diabetes",
#   "cad",
#   "htn",
#   "etiology_cirrhosis",
#   "ascites_admission",
#   "encephalopathy_admission",
#   "gi_bleed_admission",
#   "peritonitis_admission",
#   "hcc_admission",
#   "tips_admission",
#   "na_admit",
#   "k_admit",
#   "cl_admit",
#   "co2_admit",
#   "bun_admit",

#   "urine_creatinine",
#   "peak_creatinine",
#   "alt_admit",
#   "tb_admit",
#   "alb_admit",
#   "inr_admit",
#   "wbc_admit",
#   "plt_admit",
#   "urine_sodium",
#   "fena",
#   "he_grade_admission",
#   "sbp_admission",
#   "dbp_admission",
#   "rrt",  # commented out
#   "rrt_hemodialysis",
#   "icu_admission",
#   "pressor",

#   "liver_transplant_listed",
#   "liver_transplant",
#   "kidney_transplant",

#   "discharge_disposition",
#   "code_status",
#   "MELD_baseline",  # commented out
#   "MELD_Na_baseline",  # commented out
#   "MAP",
#   "CLIF_C_Score",
#   "aclf_grade",
#   "Alcoholic_hepatitis",
#   "Transplant_evalutation",
#   "Akin",
#   # "death_discharge",
#   "baseline_creatinine",
#   "los",
#   "death_in_90days_status",
#   "death_in_90days_time",
#   "albumin_given_admission",
#   "respiratory_failure")

final_terlipressin <- terlipressin_numeric %>% select(var1) 
## Warning: Using an external vector in selections was deprecated in tidyselect 1.1.0.
## ℹ Please use `all_of()` or `any_of()` instead.
##   # Was:
##   data %>% select(var1)
## 
##   # Now:
##   data %>% select(all_of(var1))
## 
## See <https://tidyselect.r-lib.org/reference/faq-external-vector.html>.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
final_terlipressin <- final_terlipressin %>% mutate(MELD_Na_baseline=ifelse(is.na(MELD_Na_baseline),median(MELD_Na_baseline,na.rm=T),MELD_Na_baseline))
# final_terlipressin <- final_terlipressin %>% mutate(albumin_given_admission=ifelse(is.na(albumin_given_admission),0,albumin_given_admission),
#                                                     respiratory_failure=ifelse(is.na(respiratory_failure),0,respiratory_failure))

order_names <- names(final_terlipressin)

Table 1

#create table one for expourse response#
T1_all_final_subgroup<- CreateTableOne(vars = all_var,strata = "group",includeNA = F,addOverall = TRUE,data = all_final, factorVars = cat_var)
#print table one 
T1_all_final_subgroup_csv <- print(T1_all_final_subgroup, nonnormal=num_var,showAllLevels = F,missing = T,quote = FALSE, noSpaces = TRUE, printToggle = FALSE)
#save 
write.csv(T1_all_final_subgroup_csv, file = '/Users/to909/Desktop/Terlipressin projects/Shelsea/Table1_all_final_11302025.csv')

matching

Balance check before

## Balance Measures
##                            Type  M.0.Un SD.0.Un  M.1.Un SD.1.Un Diff.Un
## age_admission           Contin. 58.0990 12.2669 56.1712 10.8375 -0.1666
## sex_2                    Binary  0.4115       .  0.4033       . -0.0082
## ascites_admission        Binary  0.9740       .  0.8683       . -0.1056
## etiology_cirrhosis_cat2  Binary  0.4375       .  0.5556       .  0.1181
## MELD_Na_baseline        Contin. 29.8698  7.1182 29.7572  6.3228 -0.0167
## 
## Sample sizes
##     Control Treated
## All     192     243

Balance check after

## Balance Measures
##                            Type  M.0.Un SD.0.Un  M.1.Un SD.1.Un Diff.Un
## age_admission           Contin. 58.0211 12.3078 55.8842 10.4720 -0.1870
## sex_2                    Binary  0.4158       .  0.4211       .  0.0053
## ascites_admission        Binary  0.9737       .  0.9737       .  0.0000
## etiology_cirrhosis_cat2  Binary  0.4421       .  0.5211       .  0.0789
## MELD_Na_baseline        Contin. 29.7316  7.0258 29.2947  6.4585 -0.0647
## 
## Sample sizes
##     Control Treated
## All     190     190

Table 1

#create table one for expourse response#
T1_matched_data_subgroup<- CreateTableOne(vars = all_var,strata = "group",includeNA = F,addOverall = TRUE,data = matched_data, factorVars = cat_var)
#print table one 
T1_matched_data_subgroup_csv <- print(T1_matched_data_subgroup, nonnormal=num_var,showAllLevels = F,missing = T,quote = FALSE, noSpaces = TRUE, printToggle = FALSE)
#save 
write.csv(T1_matched_data_subgroup_csv, file = '/Users/to909/Desktop/Terlipressin projects/Shelsea/Table1_matched_data_11302025.csv')

Fine and Gray event: death competing risk: liver transplant

matched_data$status_90days <- as.factor(matched_data$status_90days)
tidycmprsk::crr(Surv(time_90days,status_90days) ~ group,failcode=1,cencode=0, data = matched_data) %>% tbl_regression(exp = TRUE)
Characteristic HR1 95% CI1 p-value
group


    hrs
    terli 0.63 0.46, 0.87 0.004
1 HR = Hazard Ratio, CI = Confidence Interval

Fine and Gray event: death competing risk: liver transplant

matched_data$status_90days <- as.factor(matched_data$status_90days)
tidycmprsk::crr(Surv(time_90days,status_90days) ~ group +CLIF_C_Score ,failcode=1,cencode=0, data = matched_data) %>% tbl_regression(exp = TRUE) %>% add_n()
## 5 cases omitted due to missing values
Characteristic N HR1 95% CI1 p-value
group 375


    hrs

    terli
1.07 0.76, 1.51 0.7
CLIF_C_Score 375 1.06 1.04, 1.08 <0.001
1 HR = Hazard Ratio, CI = Confidence Interval

Fine and Gray event: death competing risk: liver transplant

matched_data$status_90days <- as.factor(matched_data$status_90days)
tidycmprsk::crr(Surv(time_90days,status_90days) ~ group + CLIF_C_Score+prophylactic_antibiotic+beta_blockers+ k_admit+ cl_admit,failcode=1,cencode=0, data = matched_data) %>% tbl_regression(exp = TRUE) %>% add_n()
## 14 cases omitted due to missing values
Characteristic N HR1 95% CI1 p-value
group 366


    hrs

    terli
1.12 0.76, 1.63 0.6
CLIF_C_Score 366 1.06 1.04, 1.08 <0.001
prophylactic_antibiotic 366


    0

    1
0.72 0.46, 1.13 0.2
beta_blockers 366


    0

    1
1.03 0.72, 1.47 0.9
k_admit 366 1.02 0.82, 1.26 0.9
cl_admit 366 0.99 0.97, 1.01 0.5
1 HR = Hazard Ratio, CI = Confidence Interval