library(MASS)

data <- read.csv("/Users/creatographer/Downloads/GUSTO_sample4p.csv")

# Question 1
htn_table <- table(data$HTN, data$DAY30)
fam_table <- table(data$FAM, data$DAY30)
# For hypertension
htn_or <- (htn_table[2, 2] / htn_table[2, 1]) / (htn_table[1, 2] / htn_table[1, 1])
# For family history
fam_or <- (fam_table[2, 2] / fam_table[2, 1]) / (fam_table[1, 2] / fam_table[1, 1])

cat("Unadjusted Odds Ratio for Hypertension:", htn_or, "\n")
## Unadjusted Odds Ratio for Hypertension: 1.587791
cat("Unadjusted Odds Ratio for Family History:", fam_or, "\n")
## Unadjusted Odds Ratio for Family History: 0.7346235
# Question 2
# A.
model <- glm(DAY30 ~ SEX + AGE + DIA + HTN + SMK + FAM, family = binomial(), data = data)
coefficients <- coef(model)

equation <- paste0(
  "logit(P) = ", round(coefficients[1], 3),
  " + ", round(coefficients[2], 3), "(SEX)",
  " + ", round(coefficients[3], 3), "(AGE)",
  " + ", round(coefficients[4], 3), "(DIA)",
  " + ", round(coefficients[5], 3), "(HTN)",
  " + ", round(coefficients[6], 3), "(SMK)",
  " + ", round(coefficients[7], 3), "(FAM)"
)

cat("Logistic Regression Model Equation:\n", equation, "\n")
## Logistic Regression Model Equation:
##  logit(P) = -10.209 + -0.194(SEX) + 0.111(AGE) + 0.838(DIA) + 0.214(HTN) + 0.024(SMK) + -0.153(FAM)
# B.
# Compute adjusted odds ratio for hypertension
htn_aor <- exp(coefficients["HTN"])
cat("Adjusted Odds Ratio for Hypertension:", round(htn_aor, 3), "\n")
## Adjusted Odds Ratio for Hypertension: 1.239
#C. 
fam_aor <- exp(coefficients["FAM"])
cat("Adjusted Odds Ratio for Family History:", round(fam_aor, 3), "\n")
## Adjusted Odds Ratio for Family History: 0.858
#D. No, the adjusted odds ratios are not the same as the unadjusted odds ratios. 
# The unadjusted OR is higher than the adjusted OR. This indicates that some of the 
# increased mortality risk attributed to hypertension in the unadjusted analysis is 
# explained by other variables in the model (e.g., age, diabetes, smoking).

# Question 3
model_interaction <- glm(DAY30 ~ SEX + AGE + DIA + HTN + SMK + FAM + AGE:HTN + SMK:DIA, 
                         family = binomial(), data = data)
anova_results <- anova(model, model_interaction, test = "Chisq")
cat("Likelihood Ratio Test Results:\n")
## Likelihood Ratio Test Results:
print(anova_results)
## Analysis of Deviance Table
## 
## Model 1: DAY30 ~ SEX + AGE + DIA + HTN + SMK + FAM
## Model 2: DAY30 ~ SEX + AGE + DIA + HTN + SMK + FAM + AGE:HTN + SMK:DIA
##   Resid. Df Resid. Dev Df Deviance Pr(>Chi)
## 1       778     329.60                     
## 2       776     329.19  2  0.41279   0.8135
summary(model_interaction)
## 
## Call:
## glm(formula = DAY30 ~ SEX + AGE + DIA + HTN + SMK + FAM + AGE:HTN + 
##     SMK:DIA, family = binomial(), data = data)
## 
## Coefficients:
##              Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -10.69999    1.74825  -6.120 9.33e-10 ***
## SEX          -0.19094    0.32582  -0.586    0.558    
## AGE           0.11641    0.02464   4.725 2.30e-06 ***
## DIA           1.45489    1.23955   1.174    0.241    
## HTN           1.00566    2.63737   0.381    0.703    
## SMK           0.07027    0.23479   0.299    0.765    
## FAM          -0.13920    0.32069  -0.434    0.664    
## AGE:HTN      -0.01116    0.03708  -0.301    0.763    
## DIA:SMK      -0.27675    0.53176  -0.520    0.603    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 382.78  on 784  degrees of freedom
## Residual deviance: 329.19  on 776  degrees of freedom
## AIC: 347.19
## 
## Number of Fisher Scoring iterations: 7
final_model <- glm(DAY30 ~ SEX + AGE + DIA + HTN + SMK + FAM + AGE:HTN, 
                   family = binomial(), data = data)
cat("Final Model Coefficients:\n")
## Final Model Coefficients:
summary(final_model)
## 
## Call:
## glm(formula = DAY30 ~ SEX + AGE + DIA + HTN + SMK + FAM + AGE:HTN, 
##     family = binomial(), data = data)
## 
## Coefficients:
##              Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -10.61608    1.73825  -6.107 1.01e-09 ***
## SEX          -0.19267    0.32590  -0.591   0.5544    
## AGE           0.11673    0.02465   4.736 2.18e-06 ***
## DIA           0.83819    0.41900   2.000   0.0455 *  
## HTN           1.20536    2.60586   0.463   0.6437    
## SMK           0.02207    0.21497   0.103   0.9182    
## FAM          -0.13972    0.32088  -0.435   0.6632    
## AGE:HTN      -0.01403    0.03663  -0.383   0.7018    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 382.78  on 784  degrees of freedom
## Residual deviance: 329.45  on 777  degrees of freedom
## AIC: 345.45
## 
## Number of Fisher Scoring iterations: 7
coefficients <- coef(final_model)
equation <- paste0(
  "logit(P) = ", round(coefficients[1], 3),
  " + ", round(coefficients[2], 3), "(SEX)",
  " + ", round(coefficients[3], 3), "(AGE)",
  " + ", round(coefficients[4], 3), "(DIA)",
  " + ", round(coefficients[5], 3), "(HTN)",
  " + ", round(coefficients[6], 3), "(SMK)",
  " + ", round(coefficients[7], 3), "(FAM)",
  " + ", round(coefficients[8], 3), "(AGE:HTN)"
)

cat("Final Model Equation:\n", equation, "\n")
## Final Model Equation:
##  logit(P) = -10.616 + -0.193(SEX) + 0.117(AGE) + 0.838(DIA) + 1.205(HTN) + 0.022(SMK) + -0.14(FAM) + -0.014(AGE:HTN)
# Hypothesis - AGE:HTN: The effect of hypertension on 30-day mortality depends on the patient's age.
# Hypothesis - SMK:DIA: The effect of smoking on 30-day mortality depends on whether the patient has diabetes.
# Statistical Test Results - Likelihood Ratio Test: p=0.8135 - The interaction terms do not significantly improve the fit of the model.
# Statistical Test Results: AGE:HTN ; p=0.701 (not significant). SMK:DIA; p=0.603 (not significant).
# Interpretation (1/4) - AGE:HTN and SMK:DIA are not statistically significant. Including them does not improve the model.
# Interpretation (2/4)- Age (p<0.001): Each year of age is associated with an increased log-odds of mortality.
# Interpretation (3/4)- Diabetes (p=0.0455): Having diabetes is associated with an increased log-odds of mortality.
# Interpretation (4/4)- Hypertension, Smoking, and Family History are not statistically significant in predicting mortality in this dataset.


# Question 4
#A.
poisson_model <- glm(STE ~ SEX + AGE + DIA + HTN + SMK + FAM, family = poisson(), data = data)
summary(poisson_model)
## 
## Call:
## glm(formula = STE ~ SEX + AGE + DIA + HTN + SMK + FAM, family = poisson(), 
##     data = data)
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept)  1.4508450  0.1039682  13.955   <2e-16 ***
## SEX          0.0110885  0.0416080   0.266    0.790    
## AGE          0.0001735  0.0017413   0.100    0.921    
## DIA          0.0554304  0.0552023   1.004    0.315    
## HTN          0.0195951  0.0368562   0.532    0.595    
## SMK         -0.0032269  0.0238767  -0.135    0.892    
## FAM         -0.0515365  0.0358222  -1.439    0.150    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for poisson family taken to be 1)
## 
##     Null deviance: 645.02  on 784  degrees of freedom
## Residual deviance: 641.45  on 778  degrees of freedom
## AIC: 3175.4
## 
## Number of Fisher Scoring iterations: 4
poisson_coefficients <- coef(poisson_model)

poisson_equation <- paste0(
  "log(E(Y)) = ", round(poisson_coefficients[1], 3),
  " + ", round(poisson_coefficients[2], 3), "(SEX)",
  " + ", round(poisson_coefficients[3], 3), "(AGE)",
  " + ", round(poisson_coefficients[4], 3), "(DIA)",
  " + ", round(poisson_coefficients[5], 3), "(HTN)",
  " + ", round(poisson_coefficients[6], 3), "(SMK)",
  " + ", round(poisson_coefficients[7], 3), "(FAM)"
)

cat("Poisson Regression Model Equation:\n", poisson_equation, "\n")
## Poisson Regression Model Equation:
##  log(E(Y)) = 1.451 + 0.011(SEX) + 0(AGE) + 0.055(DIA) + 0.02(HTN) + -0.003(SMK) + -0.052(FAM)
#B. 
nb_model <- glm.nb(STE ~ SEX + AGE + DIA + HTN + SMK + FAM, data = data)
## Warning in theta.ml(Y, mu, sum(w), w, limit = control$maxit, trace =
## control$trace > : iteration limit reached
## Warning in theta.ml(Y, mu, sum(w), w, limit = control$maxit, trace =
## control$trace > : iteration limit reached
# Summary of the model
summary(nb_model)
## 
## Call:
## glm.nb(formula = STE ~ SEX + AGE + DIA + HTN + SMK + FAM, data = data, 
##     init.theta = 85263.86539, link = log)
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept)  1.4508449  0.1039715  13.954   <2e-16 ***
## SEX          0.0110885  0.0416092   0.266    0.790    
## AGE          0.0001735  0.0017413   0.100    0.921    
## DIA          0.0554303  0.0552041   1.004    0.315    
## HTN          0.0195951  0.0368572   0.532    0.595    
## SMK         -0.0032269  0.0238774  -0.135    0.892    
## FAM         -0.0515365  0.0358233  -1.439    0.150    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for Negative Binomial(85263.87) family taken to be 1)
## 
##     Null deviance: 644.99  on 784  degrees of freedom
## Residual deviance: 641.42  on 778  degrees of freedom
## AIC: 3177.4
## 
## Number of Fisher Scoring iterations: 1
## 
## 
##               Theta:  85264 
##           Std. Err.:  474079 
## Warning while fitting theta: iteration limit reached 
## 
##  2 x log-likelihood:  -3161.435
# Extract coefficients
nb_coefficients <- coef(nb_model)

# Construct the Negative Binomial regression model equation
nb_equation <- paste0(
  "log(E(Y)) = ", round(nb_coefficients[1], 3),
  " + ", round(nb_coefficients[2], 3), "(SEX)",
  " + ", round(nb_coefficients[3], 3), "(AGE)",
  " + ", round(nb_coefficients[4], 3), "(DIA)",
  " + ", round(nb_coefficients[5], 3), "(HTN)",
  " + ", round(nb_coefficients[6], 3), "(SMK)",
  " + ", round(nb_coefficients[7], 3), "(FAM)"
)

cat("Negative Binomial Regression Model Equation:\n", nb_equation, "\n")
## Negative Binomial Regression Model Equation:
##  log(E(Y)) = 1.451 + 0.011(SEX) + 0(AGE) + 0.055(DIA) + 0.02(HTN) + -0.003(SMK) + -0.052(FAM)
# C. The equations are identical because the coefficients are nearly the same.
# The key difference is that Poisson assumes equal mean and variance and the Negative Binomial accounts for overdispersion.