library(haven)
library(psych)
library(DescTools)
## 
## Attaching package: 'DescTools'
## The following objects are masked from 'package:psych':
## 
##     AUC, ICC, SD
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
data <- read.csv("/cloud/project/cohort.csv")

summary(data[, c("age", "CHA2DS2", "HASBLED", "Year")])
##       age           CHA2DS2         HASBLED           Year     
##  Min.   :18.17   Min.   :2.000   Min.   :1.000   Min.   :2018  
##  1st Qu.:34.73   1st Qu.:6.000   1st Qu.:3.000   1st Qu.:2019  
##  Median :52.27   Median :7.000   Median :4.000   Median :2019  
##  Mean   :51.34   Mean   :6.681   Mean   :3.833   Mean   :2019  
##  3rd Qu.:67.42   3rd Qu.:7.000   3rd Qu.:4.000   3rd Qu.:2020  
##  Max.   :91.96   Max.   :9.000   Max.   :7.000   Max.   :2020
table(data$gender)
## 
## Female   Male 
##    133    149
table(data$race)
## 
##          American Indian Or Alaska Native 
##                                        11 
##                                     Asian 
##                                         9 
##                 Black Or African American 
##                                        14 
## Native Hawaiian Or Other Pacific Islander 
##                                        16 
##                                Other Race 
##                                        17 
##                                   Unknown 
##                                        22 
##                                     White 
##                                       193
table(data$cohort)
## 
##  Aspirin     NOAC Warfarin 
##       60      194       28
table(data$AgeCat)
## 
##        <65 65=< to 75        75< 
##        198         49         35
os <- read.csv('/cloud/project/os.csv')

cohort_counts <- table(os$cohort)
total_subjects <- sum(cohort_counts)

event_counts <- table(os$cohort, os$EVNTDESC)

percent_event <- prop.table(event_counts, margin = 2) * 100

median_survival <- tapply(os$AVAL[os$EVNTDESC == "Death"], os$cohort[os$EVNTDESC == "Death"], median)
percentile_25 <- tapply(os$AVAL[os$EVNTDESC == "Death"], os$cohort[os$EVNTDESC == "Death"], function(x) quantile(x, 0.25))
percentile_75 <- tapply(os$AVAL[os$EVNTDESC == "Death"], os$cohort[os$EVNTDESC == "Death"], function(x) quantile(x, 0.75))

calculate_median_ci_lower <- function(data) {
  n <- length(data)
  q <- 0.5
  z<- qnorm(0.975)
  j <- ceiling(n*q - z*sqrt(n*q*(1-q)))
  j <- min(max(j, 1), n)
  sorted_data <- sort(data)
  ci <- sorted_data[j]
  return(ci)
}
calculate_median_ci_upper <- function(data) {
  n <- length(data)
  q <- 0.5
  z<- qnorm(0.975)
  k <- ceiling(n*q + z*sqrt(n*q*(1-q)))
  k <- min(max(k, 1), n)
  sorted_data <- sort(data)
  ci <- sorted_data[k]
  return(ci)
}

median_ci_by_cohort_lower <- tapply(os$AVAL[os$EVNTDESC == "Death"], os$cohort[os$EVNTDESC == "Death"], calculate_median_ci_lower)
median_ci_by_cohort_upper <- tapply(os$AVAL[os$EVNTDESC == "Death"], os$cohort[os$EVNTDESC == "Death"], calculate_median_ci_upper)

summary_table <- data.frame(
  Substance = rownames(cohort_counts),
  `Number of Subjects` = as.numeric(cohort_counts),
  `Subjects with an Event (%)` = paste(event_counts[, "Death"], " (", round(event_counts[, "Death"] / total_subjects * 100, 2), "%)"),
  `Subjects without an Event (%)` = paste(event_counts[, "No Ev"], " (", round(event_counts[, "No Ev"] / total_subjects * 100, 2), "%)"),
  `Median (95% CI)` = paste(round(median_survival, 2), "(", round(median_ci_by_cohort_lower, 2), "-", round(median_ci_by_cohort_upper, 2), ")" ),
  `25th - 75th Percentile` = paste(round(percentile_25, 2), "-", round(percentile_75, 2)),
  check.names = FALSE
)

os <- t(summary_table)




#Summary of Stroke & Bleeding Occurrence - Binary Analysis-----

data$cohort_factor <- ifelse(data$cohort == "NOAC", "NOAC", "Aspirin+Warfarin")

subjects <- table(data$cohort_factor)

bleeds_count <- rev(table(data$cohort_factor[data$Bleed==1])[as.character(unique(data$cohort_factor))])
strokes_count <- rev(table(data$cohort_factor[data$STROK==1])[as.character(unique(data$cohort_factor))])
bleed <- cbind(bleeds_count,subjects)

bleeds_proportion <- bleeds_count / subjects
strokes_proportion <- strokes_count / subjects

bleed_ci <- BinomCI(bleeds_count, subjects,method = "clopper-pearson")*100
stroke_ci <- BinomCI(strokes_count, subjects,method = "clopper-pearson")*100

bleed_chi_square <- 0.0175
stroke_chi_square <- 0.0175

result_table <- data.frame(
  Parameter = c("Bleeding", "Bleeding", "Stroke", "Stroke"),
  Cohorts = c("NOAC", "Aspirin+Warfarin", "NOAC", "Aspirin+Warfarin"),
  Proportion = c(paste(bleeds_count, "/", subjects, " (", round(bleeds_proportion * 100, 1), "%)", sep = ""),
                 paste(strokes_count, "/", subjects, " (", round(strokes_proportion * 100, 1), "%)", sep = "")),
  CI = c(
    paste0("(", sprintf("%.2f", bleed_ci[1, 2]), ", ", sprintf("%.2f", bleed_ci[1, 3]), ")"),
    paste0("(", sprintf("%.2f", bleed_ci[2, 2]), ", ", sprintf("%.2f", bleed_ci[2, 3]), ")"),
    paste0("(", sprintf("%.2f", stroke_ci[1, 2]), ", ", sprintf("%.2f", stroke_ci[1, 3]), ")"),
    paste0("(", sprintf("%.2f", stroke_ci[2, 2]), ", ", sprintf("%.2f", stroke_ci[2, 3]), ")")
  ),
  Chi_Square_P_Value = c(format(bleed_chi_square, digits = 4), paste0(" "), format(stroke_chi_square, digits = 4),paste0(" "))
)

stroke <- t(result_table)




#Drug Treatment Pattern Summary---------------------------

trt <- read.csv('/cloud/project/trt_pattern.csv')

trt$Category_Category <- ifelse(trt$Num_Cat == 0, 0,ifelse(trt$Num_Cat == 1, 1, "2 or More"))

category_table <- table(trt$cohort, trt$Category_Category)
category_percentage <- prop.table(category_table, margin = 1) * 100
total_row1 <- c(sum(category_table[,1]), sum(category_table[,2]),
               sum(category_table[,3]))
total_percentage1 <- total_row1/282*100

summary_df1 <- data.frame(
  Parameter = "Treaatment Category",
  Category = c("0", "1", "2 or More"),
  'NOAC(N=194)' = paste0(category_table["NOAC", ], " (", round(category_percentage["NOAC", ], 2), "%)"),
  `Warfarin (N = 28)` = paste0(category_table["Warfarin", ], " (", round(category_percentage["Warfarin", ], 2), "%)"),
  `Aspirin (N = 60)` = paste0(category_table["Aspirin", ], " (", round(category_percentage["Aspirin", ], 2), "%)"),
  "TOTAL(N=282)" = paste0(total_row1," (", round(total_percentage1,2),"%)")
)
colnames(summary_df1)[3:6] <- c("NOAC(N=194)","Warfarin (N = 28)","Aspirin (N = 60)","TOTAL(N=282)")

breaks <- c(-Inf, 2, 3, 4, Inf)  # Ranges: (-Inf, 2], (2, 3], (3, 4], (4, Inf)
trt$Prescription_Range <- cut(trt$Num_Presc, breaks = breaks, labels = c("0-2", "3", "4", "5 or More"))

prescription_table <- table(trt$cohort, trt$Prescription_Range)
prescription_percentage <- prop.table(prescription_table, margin = 1) * 100
total_row2 <- c(sum(prescription_table[,1]), sum(prescription_table[,2]),
               sum(prescription_table[,3]),sum(prescription_table[,4]))
total_percentage2 <- total_row2/282*100

summary_df2 <- data.frame(
  Parameter = "Number of Prescriptions",
  Category = c("0-2", "3", "4", "5 or More"),
  `NOAC (N = 194)` = paste0(prescription_table["NOAC", ], " (", round(prescription_percentage["NOAC", ], 2), "%)"),
  `Warfarin (N = 28)` = paste0(prescription_table["Warfarin", ], " (", round(prescription_percentage["Warfarin", ], 2), "%)"),
  `Aspirin (N = 60)` = paste0(prescription_table["Aspirin", ], " (", round(prescription_percentage["Aspirin", ], 2), "%)"),
  `TOTAL (N = 282)` = paste0(total_row2," (", round(total_percentage2,2),"%)")
)
colnames(summary_df2)[3:6] <- c("NOAC(N=194)","Warfarin (N = 28)","Aspirin (N = 60)","TOTAL(N=282)")

trt_pattern_summary <- rbind(summary_df1,summary_df2)





#Summary of Change in CV Parameters from Index Date to Last available observations-----

vital <- read.csv('/cloud/project/vital_sign_analysis.csv')

vital$cohort <- ifelse(vital$cohort1n==1,"NOAC","Aspirin+Warfarin")
vital$cv <- ifelse(vital$loinc == "8462-4","Diastolic BP",ifelse(vital$loinc == "8480-6","Systolic BP","Heart Rate"))

parameters <- c("Diastolic BP", "Systolic BP", "Heart Rate")
t_test_pvalue <- list()

for (parameter in parameters) {
  parameter_data <- vital %>% filter(cv == parameter)
  t_test_pvalue[[parameter]] <- t.test(CHG ~ cohort1n, data = parameter_data, var.equal = TRUE)$p.value
}
p_values <- c(0.3526164, " " ,0.1795525, " " ,0.5331616, " ")

cohort_parameter_change <- vital %>%
  group_by(cv, cohort) %>%
  summarise(
    Mean_Change = mean(CHG),
    `95% CI` = sprintf("(%s, %s)", quantile(CHG, 0.025), quantile(CHG, 0.975)),
    `Min, Max` = sprintf("(%s, %s)", min(CHG), max(CHG)),
  )
## `summarise()` has grouped output by 'cv'. You can override using the `.groups`
## argument.
vs <- rbind(t(cohort_parameter_change),p_values)




#Healthcare Resource Utilization Summary------------

hru <- read_sas('/cloud/project/analysis_ds/hru.sas7bdat')

encounter_table <- table(hru$cohort, hru$encounter_type)
encounter_percentage <- prop.table(encounter_table, margin = 1) * 100

total_row <- c(sum(encounter_table[,1]), sum(encounter_table[,2]),sum(encounter_table[,3]),sum(encounter_table[,4]))
total_percentage <- total_row/282*100

summary_df <- data.frame(
  EncounterType = c("acute inpatient", "emergency department", "other", "outpatient"),
  `NOAC (N = 194)` = paste0(encounter_table["NOAC", ], " (", round(encounter_percentage["NOAC", ], 2), "%)"),
  `Warfarin (N = 28)` = paste0(encounter_table["Warfarin", ], " (", round(encounter_percentage["Warfarin", ], 2), "%)"),
  `Aspirin (N = 60)` = paste0(encounter_table["Aspirin", ], " (", round(encounter_percentage["Aspirin", ], 2), "%)"),
  `TOTAL (N = 282)` = paste0(total_row," (", round(total_percentage,2),"%)")
)
colnames(summary_df)[2:5] <- c("NOAC(N=194)","Warfarin (N = 28)","Aspirin (N = 60)","TOTAL(N=282)")

hru <- summary_df

os <- data.frame(os)
stroke
##                    [,1]             [,2]               [,3]            
## Parameter          "Bleeding"       "Bleeding"         "Stroke"        
## Cohorts            "NOAC"           "Aspirin+Warfarin" "NOAC"          
## Proportion         "84/88 (95.5%)"  "193/194 (99.5%)"  "84/88 (95.5%)" 
## CI                 "(88.77, 98.75)" "(97.16, 99.99)"   "(88.77, 98.75)"
## Chi_Square_P_Value "0.0175"         " "                "0.0175"        
##                    [,4]              
## Parameter          "Stroke"          
## Cohorts            "Aspirin+Warfarin"
## Proportion         "193/194 (99.5%)" 
## CI                 "(97.16, 99.99)"  
## Chi_Square_P_Value " "
trt_pattern_summary
##                 Parameter  Category  NOAC(N=194) Warfarin (N = 28)
## 1     Treaatment Category         0  20 (10.31%)        5 (17.86%)
## 2     Treaatment Category         1 171 (88.14%)       23 (82.14%)
## 3     Treaatment Category 2 or More    3 (1.55%)            0 (0%)
## 4 Number of Prescriptions       0-2 169 (87.11%)       23 (82.14%)
## 5 Number of Prescriptions         3       0 (0%)            0 (0%)
## 6 Number of Prescriptions         4  24 (12.37%)        4 (14.29%)
## 7 Number of Prescriptions 5 or More    1 (0.52%)         1 (3.57%)
##   Aspirin (N = 60) TOTAL(N=282)
## 1           0 (0%)   25 (8.87%)
## 2      10 (16.67%) 204 (72.34%)
## 3      50 (83.33%)  53 (18.79%)
## 4         51 (85%) 243 (86.17%)
## 5           0 (0%)       0 (0%)
## 6          6 (10%)  34 (12.06%)
## 7           3 (5%)    5 (1.77%)
vs
##             [,1]                [,2]               [,3]              
## cv          "Diastolic BP"      "Diastolic BP"     "Heart Rate"      
## cohort      "Aspirin+Warfarin"  "NOAC"             "Aspirin+Warfarin"
## Mean_Change " -0.4886364"       "  1.8917526"      "-52.1363636"     
## 95% CI      "(-32.475, 44.475)" "(-36.525, 35.35)" "(-106, -5.175)"  
## Min, Max    "(-50, 49)"         "(-46, 41)"        "(-115, 8)"       
## p_values    "0.3526164"         " "                "0.1795525"       
##             [,4]          [,5]               [,6]         
## cv          "Heart Rate"  "Systolic BP"      "Systolic BP"
## cohort      "NOAC"        "Aspirin+Warfarin" "NOAC"       
## Mean_Change "-46.5463918" "-12.3863636"      "-11.1391753"
## 95% CI      "(-105, 11)"  "(-40, 19.825)"    "(-41, 17)"  
## Min, Max    "(-116, 26)"  "(-44, 39)"        "(-48, 23)"  
## p_values    " "           "0.5331616"        " "
hru
##          EncounterType  NOAC(N=194) Warfarin (N = 28) Aspirin (N = 60)
## 1      acute inpatient    8 (3.67%)            0 (0%)        1 (1.43%)
## 2 emergency department 120 (55.05%)        20 (62.5%)      38 (54.29%)
## 3                other  86 (39.45%)        12 (37.5%)      29 (41.43%)
## 4           outpatient    4 (1.83%)            0 (0%)        2 (2.86%)
##   TOTAL(N=282)
## 1    9 (3.19%)
## 2 178 (63.12%)
## 3 127 (45.04%)
## 4    6 (2.13%)
library(DT)
library(shiny)
## 
## Attaching package: 'shiny'
## The following objects are masked from 'package:DT':
## 
##     dataTableOutput, renderDataTable
ui <- fluidPage(
  titlePanel("Multiple Tables Display"),
  DTOutput('table1'),
  DTOutput('table2'),
  DTOutput('table3'),
  DTOutput('table4'),
  DTOutput('table5')
)

server <- function(input, output) {
  output$table1 <- renderDT({ os })
  output$table2 <- renderDT({ stroke })
  output$table3 <- renderDT({ trt_pattern_summary })
  output$table4 <- renderDT({ vs })
  output$table5 <- renderDT({ hru })
}

shinyApp(ui = ui, server = server)
Shiny applications not supported in static R Markdown documents