# Date: 4 June 2025
#Author: Julia Colombijn; checked by Jan de Leijer

#Load packages
library("tidyverse")
library("meta")
library("metafor")
library("metaplus")
library("readxl")
library("robvis")
library("spatstat")
library("Hmisc")
library("dplyr")
library("ggplot2")
library("devtools")

#Load dataset
data <- read_excel("Tiab/Analyse/dataset_sglt2i_glp1ra_combination_obs.xlsx")
obs_rob <- read_excel("Tiab/RoB/Overview RoB observationele studies.xlsx")

# Baseline data
baseline <- tibble(
  study = c("Riley et al. 2023", "Marfella et al. 2024", "Lau et al. 2022",
            "Luo et al. 2023", "Lopez et al. 2022", "Dave et al. 2021",
            "Gorgojo-Martínez et al. 2017", "Simms-Williams et al. 2024 (1)",
            "Simms-Williams et al. 2024 (2)", "Schechter et al. 2023",
            "Kobayashi et al 2023", "Liu et al. 2025", "Patel et al 2024",
            "Wright et al 2022 (1)", "Wright et al 2022 (2)",
            "Wright et al 2022 (3)", "Chaiyakunapruk et al 2025",
            "Jensen et al 2020", "Jhu et al 2024", "García-Vega et al 2024",
            "Horiuchi et al 2025"),
  n = c(311577, 443, 2888, 1674, 686, 25168, 213, 13392, 17884, 6848, 372, 416,
        14088, 1064, 15423, 6859, 439995, 16664, 142372, 15549, 131196),
  n_ma = c(311577, 443, 2888, 1674, 686, 25168, 213, 13392, 17884, 3899, 372,
           416, 14088, NA, NA, NA, 439995, 16664, 142372, NA, NA),
  FU = c(60, 9, 18, NA, 36, 9.85, 12, 9, 8.4, 81, 47, 12, 12, 40, 48, 48, NA,
         NA, NA, 20, 36),
  age = c(60, 69, 58, 53, 68, 58, 59, 57, 58, 59, 63, 63, 63, 60, 61, 60, 64,
          59, 57, 69, NA),
  sd_age = c(NA, NA, 11, 11, 8, 11, 11, 10, 10, 10, 12, 10, 11, 9, 9, 9, 11, 11,
             11, 11, NA),
  n_female = c(149274, 180, 1337, 696, 6, 13050, 99, 6097, 8456, 3067, 172, 134,
               6175, 728, 9841, 4369, 60370, 6951, 64470, 6433, NA),
  HbA1c = c(NA, 7.6, 9.0, 8.6, 8.0, 8.4, 7.4, NA, NA, 9, 8.4, 7.4, NA, 9.2, 9.0,
            9.4, 8.0, NA, 8.2, NA, NA),
  sd_HbA1c = c(NA, NA, 1.5, 2, 1.7, 1.8, 1.3, NA, NA, 1.5, 1.6, 3.1, NA, 1.7,
               1.7, 1.7, 1.7, NA, 1.9, NA, NA),
  years_of_diabetes = c(NA, 15, 8.7, 8, NA, NA, 11, 11, 11, 10, NA, 8, NA, 5, 6,
                        9, NA, 7, NA, NA, NA),
  sd_years_of_diabetes = c(NA, NA, 6, 5, NA, NA, NA, 6, 6, 5, NA, 3, NA, 5, 5,
                           4, NA, 5, NA, NA, NA)
)

################################################################################
########################### Baseline characteristics ###########################
################################################################################

# Total sample size
baseline %>%
  summarise(n = sum(n), # total N
            n_ma = sum(n_ma, na.rm = TRUE)) # N in meta-analysis

# Follow-up
baseline %>%
  summarise(min_fu = min(FU, na.rm = TRUE),
            max_fu = max(FU, na.rm = TRUE))

# Weighted mean + SD age
baseline %>%
  summarise(mean_age = weighted.mean(age, n, na.rm = TRUE),
            sd_age = weighted.mean(sd_age, n, na.rm = TRUE))

# % women
baseline %>% filter(!is.na(n_female)) %>%
  summarise(n_female = sum(n_female),
            n = sum(n),
            perc = n_female / n * 100)

# Weighted mean + SD HbA1c
baseline %>%
  summarise(mean_hba1c = weighted.mean(HbA1c, n, na.rm = TRUE),
            sd_hba1c = weighted.mean(sd_HbA1c, n, na.rm = TRUE))

# Convert HbA1c to mmol/mol
baseline <- baseline %>%
  mutate(HbA1c_mmol = (HbA1c * 10.93) - 23.5, # Convert HbA1c to mmol/mol
         HbA1c_perc_f = sd_HbA1c / HbA1c, # determine % of SD to HbA1c
         sd_HbA1c_mmol = (HbA1c_mmol * HbA1c_perc_f)) # Convert SD to mmol/mol

# weighted mean + SD HbA1c in mmol/mol 
baseline %>%
  summarise(mean_hba1c = weighted.mean(HbA1c_mmol, n, na.rm = TRUE),
            sd_hba1c = weighted.mean(sd_HbA1c_mmol, n, na.rm = TRUE))

# Weighted mean + SD DM duration
baseline %>%
  summarise(mean_dm2_years = weighted.mean(years_of_diabetes, n, na.rm = TRUE),
            sd_dm2_years = weighted.mean(sd_years_of_diabetes, n, na.rm = TRUE))

################################## Risk of bias#################################

# 
obs_rob <- obs_rob %>%
  mutate(
    across(c(D1:D7, Overall), ~ factor(.x,
                                       levels = c("Critical",
                                                  "Low",
                                                  "Moderate",
                                                  "Serious",
                                                  "No information")))
  )

# Set up PNG for RoB of observational studies
png("supp_fig_2.png", width = 14000, height = 7000, res = 1200)

# Risk of bias trafic light observational studies
rob_traffic_light(data = obs_rob, tool = "ROBINS-I")

# Close PNG device
dev.off()


############################### Primary analysis ###############################

################################################################################
################################### Efficacy ###################################
################################################################################

## Filter rows for each outcome

# Filter the data for MACE
mace_data <- data %>%
  filter(mace == 1) %>%
  mutate(high_risk = ifelse(high_risk == 1, "Very high risk", "High risk"),
         outcome = "MACE")

# Filter data for all-cause mortality
acm_data <- data %>%
  filter(acm == 1) %>%
         mutate(events_exp = acm_events_exp,
                n_exp = acm_n_exp,
                events_cont = acm_events_cont,
                n_cont = acm_n_cont,
                outcome = "ACM") %>%
  select(study, outcome, events_exp:n_cont)

# Filter data for hospitalisation for heart failure
hhf_data <- data %>%
  filter(hhf == 1) %>%
         mutate(events_exp = hhf_events_exp,
                n_exp = hhf_n_exp,
                events_cont = hhf_events_cont,
                n_cont = hhf_n_cont,
                outcome = "HHF") %>%
  select(study, outcome, events_exp:n_cont)

# Filter data for cardiovascular mortality
cvm_data <- data %>%
  filter(cvm == 1) %>%
  mutate(events_exp = cvm_events_exp,
         n_exp = cvm_n_exp,
         events_cont = cvm_events_cont,
         n_cont = cvm_n_cont,
         outcome = "CVM") %>%
  select(study, outcome, events_exp:n_cont)

# Filter data for myocardial infarction
mi_data <- data %>%
  filter(mi == 1) %>%
  mutate(events_exp = mi_events_exp,
         n_exp = mi_n_exp,
         events_cont = mi_events_cont,
         n_cont = mi_n_cont,
         outcome = "MI") %>%
  select(study, outcome, events_exp:n_cont)

# Filter data for stroke
stroke_data <- data %>%
  filter(stroke == 1) %>%
  mutate(events_exp = stroke_events_exp,
         n_exp = stroke_n_exp,
         events_cont = stroke_events_cont,
         n_cont = stroke_n_cont,
         outcome = "Stroke") %>%
  select(study, outcome, events_exp:n_cont)

# Filter data for kidney composite endpoint
kf_data <- data %>%
  filter(kf == 1) %>%
  mutate(events_exp = kf_events_exp,
         n_exp = kf_n_exp,
         events_cont = kf_events_cont,
         n_cont = kf_n_cont,
         outcome = "KF") %>%
  select(study, outcome, events_exp:n_cont)

# Create function for labels forest plot
mlabfun <- function(text, x) {
  list(bquote(paste(.(text),
                    " (Tau"^2, " = ", .(fmtx(x$tau2, digits=4)),
                    " Q = ", .(fmtx(x$QE, digits=2)),
                    ", df = ", .(x$k - x$p), ", ",
                    .(fmtp(x$QEp, digits=3, pname="p", add0=TRUE, sep=TRUE, equal=TRUE)), "; ",
                    I^2, " = ", .(fmtx(x$I2, digits=1)), "%, ",
                    ")")))}

##################################### MACE #####################################

# Fit random model
ma_mace <- rma(
  measure = "RR",   # Risk Ratio
  ai = mace_events_exp,  # Events in experimental group
  n1i = mace_n_exp,      # Total in experimental group
  ci = mace_events_cont, # Events in control group
  n2i = mace_n_cont,     # Total in control group
  slab = study,          # Study labels
  data = mace_data,      # Data frame
  method = "REML"        # Method for random-effects model
)

# Extract weights
mace_weights <- as.data.frame(paste0(fmtx(weights(ma_mace),
                                              digits = 1), "%")) %>%
  rename(weight = `paste0(fmtx(weights(ma_mace), digits = 1), "%")`) %>%
  mutate(weight_num = as.numeric(gsub("%", "", weight)),
         weight_scaled = 0.75 + weight_num * 0.06) #Add numeric weights

# Add weights to dataframe
mace_data <- cbind(mace_data, mace_weights)

# Rerun meta-analysis with weights
ma_mace <- rma(
  measure = "RR",   # Risk Ratio
  ai = mace_events_exp,  # Events in experimental group
  n1i = mace_n_exp,      # Total in experimental group
  ci = mace_events_cont, # Events in control group
  n2i = mace_n_cont,     # Total in control group
  slab = study,          # Study labels
  data = mace_data,      # Data frame
  method = "REML"        # Method for random-effects model
)

#Extract rounded estimate and CI bound
pred_mace <- predict(ma_mace, trans = exp, digits = 2)
pred_mace <- fmtx(c(pred_mace$pred, pred_mace$ci.lb,
                        pred_mace$ci.ub), digits = 2)

# Set up PNG for MACE observational studies
png("fig_1.png", width = 16000, height = 8000, res = 1200)

# Set plot parameters
par(mar = c(10, 5, 1.3, 5), mgp = c(3, 1, 0), tcl = -0.2)

# Create plot
fp_mace_obs <- forest(ma_mace,
                  xlim=c(-10, 4),
                  at=log(c(0.1, 0.5, 1, 2, 10)),
                  atransf=exp,
                  order = weight_num,
                  xlab = "",
                  lty = c(1, 1, 0),
                  ilab = cbind(mace_events_exp, mace_n_exp, 
                               mace_events_cont, mace_n_cont, weight),
                  ilab.xpos=c(-7, -6, -5, -4, -3),
                  cex = 0.80,
                  ylim=c(-2, 14),
                  ilab.pos = 2,
                  mlab = "",
                  psize = weight_scaled,
                  header = c("Study", "Risk ratio [95% CI]"),
                  showweights = FALSE)

# hide non-bold summary estimate and add it back in bold
rect(2, -2, 4, -0.5, col="white", border=NA) 
text(fp_mace_obs$textpos[2], -1,
     paste0(pred_mace_obs[1], " [", pred_mace_obs[2], ",  ",
            pred_mace_obs[3], "]"),
     pos=2, font = 2, cex = 0.80)

# Add horizontal line at the top
segments(-10, 12, 4, 12, lwd = 0.8)

# Expand margins
par(xpd = NA)

# Add labels on top
text(c(-7, -6, -5, -4, -3), 13,
     c("Events", "Total", "Events", "Total", "Weight"), cex = 0.80,
     font = 2, pos = 2)
text(c(-6.5, -4.5, 0), 14,
     c("Combination therapy", "Monotherapy", "Risk ratio"),
     cex = 0.80, font = 2)
text(0, 13, c("MH Random, 95% CI"), cex = 0.80, font = 2)

# Add outcome labels
text(c(-10), c(11), c("Major adverse cardiovascular events"),
     pos = 4, font = 2, cex = 0.80)

# Add Total labels:
text(-10, -1, pos = 4, "Total (95% CI)", font = 2, cex = 0.80)

#Add text for total events
text(c(-6, -4), -1, c(sum(mace_obs_data$mace_n_exp),
                          sum(mace_obs_data$mace_n_cont)), pos = 2,
     font = 2, cex = 0.80)

text(c(-7, -5), -1, c(sum(mace_obs_data$mace_events_exp),
                          sum(mace_obs_data$mace_events_cont)), pos = 2,
     cex = 0.80)

# Extract p-value heterogeneity statistics
p_mace_het <- fmtp(mace_obs$QEp, digits = 2, pname = "", add0 = TRUE,
                   sep = TRUE, equal = TRUE)

#Add heterogeneity statistics
text(-10, -2, pos = 4,
     bquote(paste("Heterogeneity: ",
                  "Tau"^2, " = ", .(fmtx(mace_obs$tau2, digits = 2)), "; ",
                  "Chi"^2, " = ", .(fmtx(mace_obs$QE, digits = 2)),
                  ", df = ", .(mace_obs$k - mace_obs$p),
                  " (", italic(p), .(p_mace_het), "); ",
                  I^2, " = ", .(round(mace_obs$I2)), "%")),
     cex = 0.80)

# Extract p-value overall effect
p_mace_oe <- fmtp(mace_obs$pval, digits = 2, pname = "", add0 = TRUE,
                  sep = TRUE, equal = TRUE)


text(-10, -3, pos = 4,
     bquote(paste("Test for overall effect: ",
                  "Z = ", .(fmtx(mace_obs$zval, digits = 2)),
                  " (", italic(p), .(p_mace_oe), ")")),
     cex = 0.80)


# Add label for axes
text(log(c(0.1, 10)), -5,
     c("Favours combination of SGLT-2 inhibitor and GLP-1 RA",
                            "Favours SGLT-2 inhibitor or GLP-1 RA monotherapy"),
     pos = c(4,2), offset = -7, cex = 0.80)

# Close PNG device
dev.off()

##################### Cardiovascular mortality, MI, Stroke #####################

# Create dataframe for CVM, MI, stroke
cvm_mi_stroke_data <-
  rbind(stroke_data, mi_data, cvm_data)

# Create factor of outcome
cvm_mi_stroke_data <- cvm_mi_stroke_data %>%
  mutate(outcome = case_when(outcome == "Stroke" ~ 1,
                             outcome == "MI" ~ 2,
                             outcome == "CVM" ~ 3))

# Fit random effects model for CVM
ma_cvm <- rma(
  measure = "RR",   # Risk Ratio
  ai = events_exp,  # Events in experimental group
  n1i = n_exp,      # Total in experimental group
  ci = events_cont, # Events in control group
  n2i = n_cont,     # Total in control group
  slab = study,          # Study labels
  data = cvm_data,      # Data frame
  method = "REML"        # Method for random-effects model
)

# Extract point estimate and confidence intervals CVM
pred_cvm <- predict(ma_cvm, transf = exp, digits = 2)
pred_cvm <- fmtx(c(pred_cvm$pred, pred_cvm$ci.lb,
                       pred_cvm$ci.ub), digits=2)

# Fit random effects model for MI
ma_mi <- rma(
  measure = "RR",   # Risk Ratio
  ai = events_exp,  # Events in experimental group
  n1i = n_exp,      # Total in experimental group
  ci = events_cont, # Events in control group
  n2i = n_cont,     # Total in control group
  slab = study,          # Study labels
  data = mi_data,      # Data frame
  method = "REML"        # Method for random-effects model
)

# Extract point estimate and confidence intervals MI
pred_mi <- predict(ma_mi, transf = exp, digits = 2)
pred_mi <- fmtx(c(pred_mi$pred, pred_mi$ci.lb,
                      pred_mi$ci.ub), digits=2)

# Fit random effects model for stroke
ma_stroke <- rma(
  measure = "RR",   # Risk Ratio
  ai = events_exp,  # Events in experimental group
  n1i = n_exp,      # Total in experimental group
  ci = events_cont, # Events in control group
  n2i = n_cont,     # Total in control group
  slab = study,          # Study labels
  data = stroke_data,      # Data frame
  method = "REML"        # Method for random-effects model
)

# Extract point estimate and confidence intervals Stroke
pred_stroke <- predict(ma_stroke, transf = exp, digits = 2)
pred_stroke <- fmtx(c(pred_stroke$pred, pred_stroke$ci.lb,
                          pred_stroke$ci.ub), digits=2)

#Extract weights
cvm_weights <- as.data.frame(paste0(fmtx(weights(ma_cvm),
                                         digits = 1), "%")) %>% #CVM
  rename(weight = `paste0(fmtx(weights(ma_cvm), digits = 1), "%")`)

mi_weights <- as.data.frame(paste0(fmtx(weights(ma_mi),
                                        digits = 1), "%")) %>% #MI
  rename(weight = `paste0(fmtx(weights(ma_mi), digits = 1), "%")`)

stroke_weights <- as.data.frame(paste0(fmtx(weights(ma_stroke),
                                            digits = 1), "%")) %>% #Stroke
  rename(weight = `paste0(fmtx(weights(ma_stroke), digits = 1), "%")`)

#create dataframe of ordered weights
weights_cvm_mi_stroke <- rbind(stroke_weights, mi_weights, cvm_weights) %>%
  mutate(weight_num = as.numeric(gsub("%", "", weight)), #make weights numeric
         weight_scaled = 0.7 + 0.02 * weight_num)

# Add weights to df
cvm_mi_stroke_data <- cbind(cvm_mi_stroke_data,
                                weights_cvm_mi_stroke)

# Sort variabels by weight
cvm_mi_stroke_data <- cvm_mi_stroke_data %>%
  arrange(outcome, desc(weight_num))

# Fit random effects model for all outcomes
cvm_mi_stroke <- rma(
  measure = "RR",   # Risk Ratio
  ai = events_exp,  # Events in experimental group
  n1i = n_exp,      # Total in experimental group
  ci = events_cont, # Events in control group
  n2i = n_cont,     # Total in control group
  slab = study,          # Study labels
  data = cvm_mi_stroke_data,      # Data frame
  method = "REML"        # Method for random-effects model
)

# Set up png for observational data for CVM, MI, and stroke
png("fig_2.png", width = 16000, height = 18000, res = 1200)

# Expand margins
par(xpd = TRUE)

# Create forest plot for CVM, MI, stroke
forest(cvm_mi_stroke,
       xlim = c(-10, 4),
       at = log(c(0.1, 0.5, 1, 2, 10)),
       atransf = exp,
       order = outcome,
       xlab = "",
       lty = c(1, 1, 0),
       ilab = cbind(events_exp, n_exp, events_cont, n_cont,
                    weight),
       ilab.xpos = c(-7, -6, -5, -4, -3),
       cex = 0.80,
       ylim = c(-2, 32),
       rows = c(0:6, 13:19, 26:28),
       mlab = "",
       psize = weight_scaled,
       header = c("Study", "Risk ratio [95% CI]"),
       showweights = FALSE,
       addfit = FALSE)

# Add horizontal line at the top
segments(-10, 30, 4, 30, lwd = 0.8)

# Add labels on top
text(c(-7, -6, -5, -4, -3), 31,
     c("Events", "Total", "Events", "Total", "Weight"), cex = 0.80, font = 2)
text(c(-6.5, -4.5, 0), 32,
     c("Combination therapy", "Monotherapy", "Risk ratio"), cex = 0.80,
     font = 2)
text(0, 31, c("MH Random, 95% CI"), cex = 0.80, font = 2)

# Add pooled effect estimates per outcome
addpoly(ma_cvm, row = 24, cex = 0.80)
addpoly(ma_mi, row = 11, cex = 0.80)
addpoly(ma_stroke, row = -2, cex = 0.80)

#Hide study labels and model 
rect(-10, 29, -7.25, -3, col = "White", border = NA)

# Add outcome labels
text(c(-10), c(29, 20, 7),
     c("Cardiovascular mortality",
       "Myocardial infarction",
       "Stroke"), pos = 4, font = 2, cex = 0.80)

# Add study labels
text(c(-10), c(0:6, 13:19, 26:28),
     c("Riley et al (2023) [41]", "Chaiyakunapruk et al (2025) [29]",
       "Dave et al (2021) [30]", "Simms-Williams et al (2024b) [43]",
       "Simms-Williams et al (2024a) [43]", "Luo et al (2023) [38]",
       "Liu et al (2025) [36]", "Riley et al (2023) [41]",
       "Chaiyakunapruk et al (2025) [29]", "Dave et al (2021) [30]", 
       "Simms-Williams et al (2024b [43]", "Simms-Williams et al (2024a) [43]",
       "Luo et al (2023) [38]", "Liu et al (2025) [36]",
       "Simms-Williams et al (2024b) [43]", "Simms-Williams et al (2024a) [43]",
       "Liu et al (2025) [36]"), cex = 0.80, pos = 4)

# Hide point estimates RE
rect(1, c(25, 12, -1), 4, c(23, 10, -3), col = "White", border = NA)

# Add pooled effect estimates estimates in bold

text(4, 24,
     paste0(pred_cvm[1], " [", pred_cvm[2], ",  ",
            pred_cvm[3], "]"), pos = 2, cex = 0.80, font = 2) # CVM

text(4, 11,
     paste0(pred_mi[1], " [", pred_mi[2], ",  ",
            pred_mi[3], "]"), pos = 2, cex = 0.80, font = 2) # MI

text(4, -2,
     paste0(pred_stroke[1], " [", pred_stroke[2], ",  ",
            pred_stroke[3], "]"), pos = 2, cex = 0.80, font = 2) # Stroke

# Add Total labels:
text(-10, c(24, 11, -2), pos = 4, "Total (95% CI)", font = 2, cex = 0.80)

#Add text for total number of patients CVM
text(c(-6, -4), 24, c(sum(cvm_data$n_exp),
                      sum(cvm_data$n_cont)),
     font = 2, cex = 0.80)

# Add text for total number of events CVM
text(c(-7, -5), 24, c(sum(cvm_data$events_exp),
                      sum(cvm_data$events_cont)),
     cex = 0.80)

#Add text for total number of patients MI
text(c(-6, -4), 11, c(sum(mi_data$n_exp),
                     sum(mi_data$n_cont)),
     font = 2, cex = 0.80)

# Add text for total number of events MI
text(c(-7, -5), 11, c(sum(mi_data$events_exp),
                     sum(mi_data$events_cont)),
     cex = 0.80)

#Add text for total number of patients Stroke
text(c(-6, -4), -2, c(sum(stroke_data$n_exp),
                      sum(stroke_data$n_cont)),
     font = 2, cex = 0.80)

# Add text for total number of events Stroke
text(c(-7, -5), -2, c(sum(stroke_data$events_exp),
                      sum(stroke_data$events_cont)),
     cex = 0.80)

# Cardiovascular mortality

# Extract p-values
p_cvm_het <- fmtp(ma_cvm$QEp, digits = 2, pname = "", add0 = TRUE,
                  sep = TRUE, equal = TRUE)
p_cvm_oe <- fmtp(ma_cvm$pval, digits = 2, pname = "", add0 = TRUE, sep = TRUE,
                 equal = TRUE)

# Heterogeneity
text(-10, 23, pos = 4, cex = 0.80,
     bquote(paste("Heterogeneity: ",
                  "Tau"^2, " = ", .(fmtx(ma_cvm$tau2, digits = 2)), "; ",
                  "Chi"^2, " = ", .(fmtx(ma_cvm$QE, digits = 2)),
                  ", df = ", .(ma_cvm$k - ma_cvm$p),
                  " (", italic(p), .(p_cvm_het), "); ",
                  I^2, " = ", .(round(ma_cvm$I2)), "%")))

# Overall effect
text(-10, 22, pos = 4, cex = 0.80,
     bquote(paste("Test for overall effect: ",
                  "Z = ", .(fmtx(ma_cvm$zval, digits = 2)),
                  " (", italic(p), .(p_cvm_oe), ")")))

# Myocardial infarction

# Extract p-values
p_mi_het <- fmtp(ma_mi$QEp, digits = 2, pname = "", add0 = TRUE, sep = TRUE,
                 equal = TRUE)
p_mi_oe  <- fmtp(ma_mi$pval, digits = 2, pname = "", add0 = TRUE, sep = TRUE,
                 equal = TRUE)

# Heterogeneity
text(-10, 10, pos = 4, cex = 0.80,
     bquote(paste("Heterogeneity: ",
                  "Tau"^2, " = ", .(fmtx(ma_mi$tau2, digits = 2)), "; ",
                  "Chi"^2, " = ", .(fmtx(ma_mi$QE, digits = 2)),
                  ", df = ", .(ma_mi$k - ma_mi$p),
                  " (", italic(p), .(p_mi_het), "); ",
                  I^2, " = ", .(round(ma_mi$I2)), "%")))

# Overall effect
text(-10, 9, pos = 4, cex = 0.80,
     bquote(paste("Test for overall effect: ",
                  "Z = ", .(fmtx(ma_mi$zval, digits = 2)),
                  " (", italic(p), .(p_mi_oe), ")")))

# Stroke

# Extract p-values
p_stroke_het <- fmtp(ma_stroke$QEp, digits = 2, pname = "", add0 = TRUE,
                     sep = TRUE, equal = TRUE)
p_stroke_oe  <- fmtp(ma_stroke$pval, digits = 2, pname = "", add0 = TRUE,
                     sep = TRUE, equal = TRUE)

# Heterogeneity
text(-10, -3, pos = 4, cex = 0.80,
     bquote(paste("Heterogeneity: ",
                  "Tau"^2, " = ", .(fmtx(ma_stroke$tau2, digits = 2)), "; ",
                  "Chi"^2, " = ", .(fmtx(ma_stroke$QE, digits = 2)),
                  ", df = ", .(ma_stroke$k - ma_stroke$p),
                  " (", italic(p), .(p_stroke_het), "); ",
                  I^2, " = ", .(round(ma_stroke$I2)), "%")))

# Overall effect
text(-10, -4, pos = 4, cex = 0.80,
     bquote(paste("Test for overall effect: ",
                  "Z = ", .(fmtx(ma_stroke$zval, digits = 2)),
                  " (", italic(p), .(p_stroke_oe), ")")))

# Add label for axes
text(log(c(0.1, 10)), -5, c("Favours combination of SGLT-2 inhibitor and GLP-1 RA",
                            "Favours SGLT-2 inhibitor or GLP-1 RA monotherapy"),
     pos = c(4,2), offset = -7, cex = 0.80)

# Close PNG device
dev.off()

######################### All-cause mortality, HHF, KF #########################

# Create dataframe for all-cause mortality, HHF, KF
acm_hhf_kf_data <-
  rbind(acm_data, kf_data, hhf_data) 

# Create factor of outcome
acm_hhf_kf_data <- acm_hhf_kf_data %>%
  mutate(outcome = case_when(outcome == "HHF" ~ 1,
                             outcome == "KF" ~ 2,
                             outcome == "ACM" ~ 3))

# Fit random effects model for HHF
ma_hhf <- rma(
  measure = "RR",   # Risk Ratio
  ai = events_exp,  # Events in experimental group
  n1i = n_exp,      # Total in experimental group
  ci = events_cont, # Events in control group
  n2i = n_cont,     # Total in control group
  slab = study,          # Study labels
  data = hhf_data,      # Data frame
  method = "REML"        # Method for random-effects model
)

# Extract point estimate and confidence intervals HHF
pred_hhf <- predict(ma_hhf, transf = exp, digits = 2)
pred_hhf <- fmtx(c(pred_hhf$pred, pred_hhf$ci.lb,
                       pred_hhf$ci.ub), digits=2)

# Fit random effects model for KF
ma_kf <- rma(
  measure = "RR",   # Risk Ratio
  ai = events_exp,  # Events in experimental group
  n1i = n_exp,      # Total in experimental group
  ci = events_cont, # Events in control group
  n2i = n_cont,     # Total in control group
  slab = study,          # Study labels
  data = kf_data,      # Data frame
  method = "REML"        # Method for random-effects model
)

# Extract point estimate and confidence intervals KF
pred_kf <- predict(ma_kf, transf = exp, digits = 2)
pred_kf <- fmtx(c(pred_kf$pred, pred_kf$ci.lb,
                      pred_kf$ci.ub), digits=2)

# Fit random effects model for ACM
ma_acm <- rma(
  measure = "RR",   # Risk Ratio
  ai = events_exp,  # Events in experimental group
  n1i = n_exp,      # Total in experimental group
  ci = events_cont, # Events in control group
  n2i = n_cont,     # Total in control group
  slab = study,          # Study labels
  data = acm_data,      # Data frame
  method = "REML"        # Method for random-effects model
)

# Extract point estimate and confidence intervals ACM
pred_acm <- predict(ma_acm, transf = exp, digits = 2)
pred_acm <- fmtx(c(pred_acm$pred, pred_acm$ci.lb,
                       pred_acm$ci.ub), digits=2)

# Extract weights
hhf_weights <- as.data.frame(paste0(fmtx(weights(ma_hhf),
                                         digits = 1), "%")) %>% #HHF
  rename(weight = `paste0(fmtx(weights(ma_hhf), digits = 1), "%")`)

kf_weights <- as.data.frame(paste0(fmtx(weights(ma_kf),
                                        digits = 1), "%")) %>% #KF
  rename(weight = `paste0(fmtx(weights(ma_kf), digits = 1), "%")`)

acm_weights <- as.data.frame(paste0(fmtx(weights(ma_acm),
                                         digits = 1), "%")) %>% #ACM
  rename(weight = `paste0(fmtx(weights(ma_acm), digits = 1), "%")`)

# Create dataframe of ordered weights
weights_acm_hhf_kf <- rbind(acm_weights, kf_weights, hhf_weights) %>%
  mutate(weight_num = as.numeric(gsub("%", "", weight)), #make weights numeric
         weight_scaled = 0.7 + 0.02 * weight_num)

# Add weights to df
acm_hhf_kf_data <- cbind(acm_hhf_kf_data, weights_acm_hhf_kf)

# Sort variabels by weight
acm_hhf_kf_obs_data <- acm_hhf_kf_obs_data %>%
  arrange(outcome, desc(weight_num))

# Fit random effects model for all outcomes
ma_acm_hhf_kf <- rma(
  measure = "RR",   # Risk Ratio
  ai = events_exp,  # Events in experimental group
  n1i = n_exp,      # Total in experimental group
  ci = events_cont, # Events in control group
  n2i = n_cont,     # Total in control group
  slab = study,          # Study labels
  data = acm_hhf_kf_obs_data,      # Data frame
  method = "REML"        # Method for random-effects model
)

# Set up png for observational data for HHF, KF, ACM, CVM, MI, and stroke
png("fig_3.png", width = 16000, height = 18000, res = 1200)

# Expand margins
par(xpd = TRUE)

# Create forest plot for HHF, KF, and ACM
forest(ma_acm_hhf_kf,
       xlim = c(-10, 4),
       at = log(c(0.1, 0.5, 1, 2, 10)),
       atransf = exp,
       order = outcome,
       xlab = "",
       lty = c(1, 1, 0),
       ilab = cbind(events_exp, n_exp, events_cont, n_cont,
                    weight),
       ilab.xpos = c(-7, -6, -5, -4, -3),
       cex = 0.80,
       ylim = c(-2, 39),
       rows = c(0:4, 11:18, 25:35),
       mlab = "",
       psize = weight_scaled,
       header = c("Study", "Risk ratio [95% CI]"),
       showweights = FALSE,
       addfit = FALSE)

# Add horizontal line at the top
segments(-10, 37, 4, 37, lwd = 0.8)

# Add labels on top
text(c(-7, -6, -5, -4, -3), 38,
     c("Events", "Total", "Events", "Total", "Weight"), cex = 0.80, font = 2)
text(c(-6.5, -4.5, 0), 39,
     c("Combination therapy", "Monotherapy", "Risk ratio"), cex = 0.80,
     font = 2)
text(0, 38, c("MH Random, 95% CI"), cex = 0.80, font = 2)

# Add pooled effect estimates per outcome
addpoly(ma_acm, row = 23, cex = 0.80)
addpoly(ma_kf, row = 9, cex = 0.80)
addpoly(ma_hhf, row = -2, cex = 0.80)

#Hide study labels and model 
rect(-10, 36, -7.25, -3, col = "White", border = NA)

# Add outcome labels
text(c(-10), c(36, 19, 5),
     c("All-cause mortality",
       "Kidney composite endpoint",
       "Hospitalisation for heart failure"),
     pos = 4, font = 2, cex = 0.80)

# Add study labels
text(c(-10), c(0:4, 11:18, 25:35),
     c("Patel et al (2024) [40]", "Dave et al (2021) [30]",
       "Lopez et al (2022) [37]", "Lau et al (2022) [35]",
       "Liu et al (2025) [36]", "Riley et al (2023) [41]",
       "Jhu et al (2024) [33]", "Patel et al (2024) [40]",
       "Kobayashi et al (2023) [34]", "Simms-Williams et al (2024a) [43]",
       "Schechter et al (2023) [42]", "Simms-Williams et al (2024b) [43]",
       "Lau et al (2022) [35]", "Riley et al (2023) [41]",
       "Jhu et al (2024) [33]", "Patel et al (2024) [40]",
       "Simms-Williams et al (2024b) [43]", "Simms-Williams et al (2024a) [43]",
       "Jensen et al (2020) [32]", "Lau et al (2022) [35]",
       "Dave et al (2021) [30]", "Luo et al (2023) [38]",
       "Liu et al (2025) [36]", "Gorgojo-Martínez et al (2017) [31]"),
     cex = 0.80, pos = 4)

# Hide point estimates RE
rect(1, c(24, 10, -1),
     4, c(22, 8, -3), col = "White", border = NA)

# Add pooled effect estimates estimates in bold

text(4, 23,
     paste0(pred_acm[1], " [", pred_acm[2], ",  ",
            pred_acm[3], "]"), pos = 2, cex = 0.80, font = 2) # ACM

text(4, 9,
     paste0(pred_kf[1], " [", pred_kf[2], ",  ",
            pred_kf[3], "]"), pos = 2, cex = 0.80, font = 2) # KF

text(4, -2,
     paste0(pred_hhf[1], " [", pred_hhf[2], ",  ",
            pred_hhf[3], "]"), pos = 2, cex = 0.80, font = 2) # HHF

# Add Total labels:
text(-10, c(23, 9, -2), pos = 4, "Total (95% CI)", font = 2,
     cex = 0.80)

#Add text for total number of patients ACM
text(c(-6, -4), 23, c(sum(acm_data$n_exp),
                      sum(acm_data$n_cont)),
     font = 2, cex = 0.80)

# Add text for total number of events ACM
text(c(-7, -5), 23, c(sum(acm_data$events_exp),
                      sum(acm_data$events_cont)),
     cex = 0.80)

#Add text for total number of patients KF
text(c(-6, -4), 9, c(sum(kf_data$n_exp),
                      sum(kf_data$n_cont)),
     font = 2, cex = 0.80)

# Add text for total number of events KF
text(c(-7, -5), 9, c(sum(kf_data$events_exp),
                      sum(kf_data$events_cont)),
     cex = 0.80)

#Add text for total number of patients HHF
text(c(-6, -4), -2, c(sum(hhf_data$n_exp),
                      sum(hhf_data$n_cont)),
     font = 2, cex = 0.80)

# Add text for total number of events HHF
text(c(-7, -5), -2, c(sum(hhf_data$events_exp),
                      sum(hhf_data$events_cont)),
     font = 2, cex = 0.80)

# All-cause mortality

# Extract p-values
p_acm_het <- fmtp(ma_acm$QEp, digits = 2, pname = "", add0 = TRUE, sep = TRUE,
                  equal = TRUE)
p_acm_oe  <- fmtp(ma_acm$pval, digits = 2, pname = "", add0 = TRUE, sep = TRUE,
                  equal = TRUE)

# Heterogeneity
text(-10, 22, pos = 4, cex = 0.80,
     bquote(paste("Heterogeneity: ",
                  "Tau"^2, " = ", .(fmtx(ma_acm$tau2, digits = 2)), "; ",
                  "Chi"^2, " = ", .(fmtx(ma_acm$QE, digits = 2)),
                  ", df = ", .(ma_acm$k - ma_acm$p),
                  " (", italic(p), .(p_acm_het), "); ",
                  I^2, " = ", .(round(ma_acm$I2)), "%")))

# Overall effect
text(-10, 21, pos = 4, cex = 0.80,
     bquote(paste("Test for overall effect: ",
                  "Z = ", .(fmtx(ma_acm$zval, digits = 2)),
                  " (", italic(p), .(p_acm_oe), ")")))

# Kidney failure

# Extract p-values
p_kf_het <- fmtp(ma_kf$QEp, digits = 2, pname = "", add0 = TRUE, sep = TRUE,
                 equal = TRUE)
p_kf_oe  <- fmtp(ma_kf$pval, digits = 2, pname = "", add0 = TRUE, sep = TRUE,
                 equal = TRUE)

# Heterogeneity
text(-10, 8, pos = 4, cex = 0.80,
     bquote(paste("Heterogeneity: ",
                  "Tau"^2, " = ", .(fmtx(ma_kf$tau2, digits = 2)), "; ",
                  "Chi"^2, " = ", .(fmtx(ma_kf$QE, digits = 2)),
                  ", df = ", .(ma_kf$k - ma_kf$p),
                  " (", italic(p), .(p_kf_het), "); ",
                  I^2, " = ", .(round(ma_kf$I2)), "%")))

# Overall effect
text(-10, 7, pos = 4, cex = 0.80,
     bquote(paste("Test for overall effect: ",
                  "Z = ", .(fmtx(ma_kf$zval, digits = 2)),
                  " (", italic(p), .(p_kf_oe), ")")))

# Hospitalisation for heart failure

# Extract p-values
p_hhf_het <- fmtp(ma_hhf$QEp, digits = 2, pname = "", add0 = TRUE, sep = TRUE,
                  equal = TRUE)
p_hhf_oe  <- fmtp(ma_hhf$pval, digits = 2, pname = "", add0 = TRUE, sep = TRUE,
                  equal = TRUE)

# Heterogeneity
text(-10, -3, pos = 4, cex = 0.80,
     bquote(paste("Heterogeneity: ",
                  "Tau"^2, " = ", .(fmtx(ma_hhf$tau2, digits = 2)), "; ",
                  "Chi"^2, " = ", .(fmtx(ma_hhf$QE, digits = 2)),
                  ", df = ", .(ma_hhf$k - ma_hhf$p),
                  " (", italic(p), .(p_hhf_het), "); ",
                  I^2, " = ", .(round(ma_hhf$I2)), "%")))

# Overall effect
text(-10, -4, pos = 4, cex = 0.80,
     bquote(paste("Test for overall effect: ",
                  "Z = ", .(fmtx(ma_hhf$zval, digits = 2)),
                  " (", italic(p), .(p_hhf_oe), ")")))

# Add label for axes
text(log(c(0.1, 10)), -6, c("Favours combination of SGLT-2 inhibitor and GLP-1 RA",
                            "Favours SGLT-2 inhibitor or GLP-1 RA monotherapy"),
     pos = c(4,2), offset = -7, cex = 0.80)

# Close PNG device
dev.off()

################################################################################
########################### Subgroup analyses for MACE #########################
################################################################################

# Create SGLT2i control arm
mace_data_sglt2i <- mace_data %>%
  filter(sglt2 == 1) %>% # Select rows with SGLT-2i as control
  select(-weight:-weight_scaled) %>% # Drop weight columns
  mutate(control = "SGLT-2 inhibitor",
         mace_n_cont = mace_n_sglt2,
         mace_events_cont = mace_events_sglt2)

# Create GLP-1 RA control arm
mace_data_glp1_ra <- mace_data %>%
  filter(glp_1_ra == 1) %>% # Select rows with GLP-1 RA as control
  select(-weight:-weight_scaled) %>% # Drop weight columns
  mutate(control = "GLP-1 receptor agonist",
         mace_n_cont = mace_n_glp1_ra,
         mace_events_cont = mace_events_glp1_ra)

# Fit random effects model for SGLT-2i
ma_mace_sglt2i <- rma(
  measure = "RR",   # Risk Ratio
  ai = mace_events_exp,  # Events in experimental group
  n1i = mace_n_exp,      # Total in experimental group
  ci = mace_events_sglt2, # Events in control group
  n2i = mace_n_sglt2,     # Total in control group
  slab = study,          # Study labels
  data = mace_data_sglt2i,      # Data frame
  method = "REML"        # Method for random-effects model
)

# Extract point estimate and confidence intervals SGLT2i
pred_mace_sglt2i <- predict(ma_mace_sglt2i, transf = exp, digits = 2)
pred_mace_sglt2i <- fmtx(c(pred_mace_sglt2i$pred, pred_mace_sglt2i$ci.lb,
                           pred_mace_sglt2i$ci.ub), digits=2)

# Extract weights for SGLT2i
mace_sglt2i_weights <- as.data.frame(paste0(fmtx(weights(ma_mace_sglt2i),
                                              digits = 1), "%")) %>%
  rename(weight = `paste0(fmtx(weights(ma_mace_sglt2i), digits = 1), "%")`) %>%
  mutate(weight_num = as.numeric(gsub("%", "", weight)),
         weight_scaled = 0.7 + weight_num * 0.02) #Add numeric weights

# Add weights to dataframe
mace_data_sglt2i <- cbind(mace_data_sglt2i, mace_sglt2i_weights)

# Fit random effects model for GLP-1 RA
ma_mace_glp1ra <- rma(
  measure = "RR",   # Risk Ratio
  ai = mace_events_exp,  # Events in experimental group
  n1i = mace_n_exp,      # Total in experimental group
  ci = mace_events_glp1_ra, # Events in control group
  n2i = mace_n_glp1_ra,     # Total in control group
  slab = study,          # Study labels
  data = mace_data_glp1_ra,      # Data frame
  method = "REML"        # Method for random-effects model
)

# Extract point estimate and confidence intervals GLP-1 RA
pred_mace_glp1ra <- predict(ma_mace_glp1ra, transf = exp, digits = 2)
pred_mace_glp1ra <- fmtx(c(pred_mace_glp1ra$pred, pred_mace_glp1ra$ci.lb,
                           pred_mace_glp1ra$ci.ub), digits=2)

# Extract weights for GLP-1 RA
mace_glp1ra_weights <- as.data.frame(paste0(fmtx(weights(ma_mace_glp1ra),
                                                 digits = 1), "%")) %>%
  rename(weight = `paste0(fmtx(weights(ma_mace_glp1ra), digits = 1), "%")`) %>%
  mutate(weight_num = as.numeric(gsub("%", "", weight)),
         weight_scaled = 0.7 + weight_num * 0.02) #Add numeric weights

# Add weights to dataframe
mace_data_glp1_ra <- cbind(mace_data_glp1_ra, mace_glp1ra_weights)

# bind dataframes together
mace_data_control <- rbind(mace_data_sglt2i, mace_data_glp1_ra)

mace_data_control <- mace_data_control %>%
  mutate(control_num = ifelse(control == "SGLT-2 inhibitor", 2, 1))

# order dataframe by weight 
mace_data_control <- mace_data_control %>%
  arrange(control, desc(weight_num))

# Run meta-analysis for control intervention
ma_mace_control <- rma(
  measure = "RR",   # Risk Ratio
  ai = mace_events_exp,  # Events in experimental group
  n1i = mace_n_exp,      # Total in experimental group
  ci = mace_events_cont, # Events in control group
  n2i = mace_n_cont,     # Total in control group
  slab = study,          # Study labels
  data = mace_data_control,      # Data frame
  method = "REML"        # Method for random-effects model
)

# Set up PNG for forest plot for MACE by control intervention
png("fig_4.png", width = 16000, height = 8500, res = 1200)

# Create forest plot 
fp_mace_control <- forest(ma_mace_control,
                          xlim = c(-10, 4),
                          at = log(c(0.1, 0.5, 1, 2, 10)),
                          atransf = exp,
                          order = control_num,
                          efac = 0.5,
                          xlab = "",
                          lty = c(1, 1, 0),
                          ilab = cbind(mace_events_exp, mace_n_exp,
                                       mace_events_cont, mace_n_cont,
                                       weight),
                          ilab.xpos = c(-7, -6, -5, -4, -3),
                          cex = 0.80,
                          ylim = c(-2, 20),
                          rows = c(0:3, 10:16),
                          mlab = "",
                          psize = weight_scaled,
                          header = c("Study", "Risk ratio [95% CI]"),
                          showweights = FALSE,
                          addfit = FALSE)

# Add pooled effect of SGLT2-i and GLP-1 RA
addpoly(ma_mace_sglt2i, row = 8, cex = 0.80)
addpoly(ma_mace_glp1ra, row = -2, cex = 0.80)

# hide non-bold summary estimates and study labels
rect(-10, 17, -7.25, -3, col = "White", border = NA)

# Hide point estimates RE
rect(2.4, c(9, -1), 4, c(7, -3), col = "White", border = NA)
rect(-10, c(9, -1), -8, c(7, -3), col = "White", border = NA)


# Place summary estimates back in bold
text(fp_mace_control$textpos[2], 8,
     paste0(pred_mace_sglt2i[1], " [", pred_mace_sglt2i[2], ",  ",
            pred_mace_sglt2i[3], "]"),
     pos=2, font = 2, cex = 0.80)

text(fp_mace_control$textpos[2], -2,
     paste0(pred_mace_glp1ra[1], " [", pred_mace_glp1ra[2], ",  ",
            pred_mace_glp1ra[3], "]"),
     pos=2, font = 2, cex = 0.80)

# Add horizontal line at the top
segments(-10, 18, 4, 18, lwd = 0.8)

# Expand margins
par(xpd = NA)

# Add labels on top
text(c(-7, -6, -5, -4, -3), 19,
     c("Events", "Total", "Events", "Total", "Weight"), cex = 0.80,
     font = 2)
text(c(-6.5, -4.5, 0), 20,
     c("Combination therapy", "Monotherapy", "Risk ratio"),
     cex = 0.80, font = 2)
text(0, 19, c("MH Random, 95% CI"), cex = 0.80, font = 2)

# Add subgroup labels
text(c(-10), c(17, 4), c("SGLT-2 inhibitor", "GLP-1 receptor agonist"),
     pos = 4, font = 2, cex = 0.80)

# Add study labels
text(-10, c(0:3, 10:16),
     c("Simms-Williams et al (2024a) [43]", "Jensen et al (2020) [43]",
       "Lau et al (2022) [35]", "Marfella et al (2024) [39]",
       "Chaiyakunapruk et al (2025) [29]", "Jhu et al (2024) [33]",
       "Simms-Williams et al (2024b) [43]", "Lopez et al (2022) [37]",
       "Liu et al (2025) [36]", "Jensen et al (2020) [32]",
       "Marfella et al (2024) [39]"), cex = 0.80, pos = 4)

# Add subtotal labels
text(-10, c(8, -2), "Total (95% CI)", font = 2, cex = 0.80, pos = 4)

#Add text for total events
text(c(-6, -4), 8, c(sum(mace_data_sglt2i$mace_n_exp),
                      sum(mace_data_sglt2i$mace_n_cont)), font = 2, cex = 0.80)

text(c(-7, -5), 8, c(sum(mace_data_sglt2i$mace_events_exp),
                      sum(mace_data_sglt2i$mace_events_cont)), cex = 0.80)

text(c(-6, -4), -2, c(sum(mace_data_glp1_ra$mace_n_exp),
                     sum(mace_data_glp1_ra$mace_n_cont)), font = 2, cex = 0.80)

text(c(-7, -5), -2, c(sum(mace_data_glp1_ra$mace_events_exp),
                     sum(mace_data_glp1_ra$mace_events_cont)), cex = 0.80)

# Add sum of weights
text(-3, c(8, -2), "100%", cex = 0.80, font = 2)

# SGLT-2 inhibitors
# Extract p-values
p_sglt2i_het <- fmtp(ma_mace_sglt2i$QEp, digits = 2, pname = "", add0 = TRUE,
                     sep = TRUE, equal = TRUE)
p_sglt2i_oe  <- fmtp(ma_mace_sglt2i$pval, digits = 2, pname = "", add0 = TRUE,
                     sep = TRUE, equal = TRUE)

# Heterogeneity
text(-10, 7, pos = 4, cex = 0.80,
     bquote(paste("Heterogeneity: ",
                  "Tau"^2, " = ", .(fmtx(ma_mace_sglt2i$tau2, digits = 2)), "; ",
                  "Chi"^2, " = ", .(fmtx(ma_mace_sglt2i$QE, digits = 2)),
                  ", df = ", .(ma_mace_sglt2i$k - ma_mace_sglt2i$p),
                  " (", italic(p), .(p_sglt2i_het), "); ",
                  I^2, " = ", .(round(ma_mace_sglt2i$I2)), "%")))

# Overall effect
text(-10, 6, pos = 4, cex = 0.80,
     bquote(paste("Test for overall effect: ",
                  "Z = ", .(fmtx(ma_mace_sglt2i$zval, digits = 2)),
                  " (", italic(p), .(p_sglt2i_oe), ")")))

# GLP-1 RAs
# Extract p-values
p_glp1ra_het <- fmtp(ma_mace_glp1ra$QEp, digits = 2, pname = "", add0 = TRUE,
                     sep = TRUE, equal = TRUE)
p_glp1ra_oe  <- fmtp(ma_mace_glp1ra$pval, digits = 2, pname = "", add0 = TRUE,
                     sep = TRUE, equal = TRUE)

# Heterogeneity
text(-10, -3, pos = 4, cex = 0.80,
     bquote(paste("Heterogeneity: ",
                  "Tau"^2, " = ", .(fmtx(ma_mace_glp1ra$tau2, digits = 2)), "; ",
                  "Chi"^2, " = ", .(fmtx(ma_mace_glp1ra$QE, digits = 2)),
                  ", df = ", .(ma_mace_glp1ra$k - ma_mace_glp1ra$p),
                  " (", italic(p), .(p_glp1ra_het), "); ",
                  I^2, " = ", .(round(ma_mace_glp1ra$I2)), "%")))

# Overall effect
text(-10, -4, pos = 4, cex = 0.80,
     bquote(paste("Test for overall effect: ",
                  "Z = ", .(fmtx(ma_mace_glp1ra$zval, digits = 2)),
                  " (", italic(p), .(p_glp1ra_oe), ")")))

# Add label for axes
text(log(c(0.1, 10)), -5,
     c("Favours combination of SGLT-2 inhibitor and GLP-1 RA",
                            "Favours SGLT-2 inhibitor or GLP-1 RA monotherapy"),
     pos = c(4,2), offset = -7, cex = 0.80)

# Close PNG device
dev.off()

############################ History of CVD, HF, CKD ########################### 

# Filter studies with patients at very high risk of CVD
mace_very_high_risk_data <- data %>%
  filter(high_risk_mace == 1 & high_risk == 1) %>%
  select(study, high_risk, mace_events_exp, mace_n_exp, mace_events_cont,
         mace_n_cont)

# Run meta-analysis for patients with history of CVD
ma_mace_very_high_risk <- rma(
  measure = "RR",   # Risk Ratio
  ai = mace_events_exp,  # Events in experimental group
  n1i = mace_n_exp,      # Total in experimental group
  ci = mace_events_cont, # Events in control group
  n2i = mace_n_cont,     # Total in control group
  slab = study,          # Study labels
  data = mace_very_high_risk_data,      # Data frame
  method = "REML"        # Method for random-effects model
)

# Extract weights
mace_very_high_risk_weights <- as.data.frame(paste0(fmtx(weights(ma_mace_very_high_risk),
                                                 digits = 1), "%")) %>%
  rename(weight = `paste0(fmtx(weights(ma_mace_very_high_risk), digits = 1), "%")`) %>%
  mutate(weight_num = as.numeric(gsub("%", "", weight)),
         weight_scaled = 0.7 + weight_num * 0.02) #Add numeric weights

#Extract rounded estimate and CI bound
pred_mace_very_high_risk <- predict(ma_mace_very_high_risk, transf = exp, digits = 2)
pred_mace_very_high_risk <- fmtx(c(pred_mace_very_high_risk$pred, pred_mace_very_high_risk$ci.lb,
                                   pred_mace_very_high_risk$ci.ub), digits=2)

# Add weights to dataframe
mace_very_high_risk_data <- cbind(mace_very_high_risk_data,
                             mace_very_high_risk_weights)

# Filter studies with patients at high risk of CVD
mace_high_risk_data <- data %>%
  filter(high_risk_mace == 1 & high_risk == 0) %>%
  select(study, high_risk, mace_events_exp, mace_n_exp, mace_events_cont,
         mace_n_cont)

# Run meta-analysis for patients without a history of CVD
ma_mace_high_risk <- rma(
  measure = "RR",   # Risk Ratio
  ai = mace_events_exp,  # Events in experimental group
  n1i = mace_n_exp,      # Total in experimental group
  ci = mace_events_cont, # Events in control group
  n2i = mace_n_cont,     # Total in control group
  slab = study,          # Study labels
  data = mace_high_risk_data,      # Data frame
  method = "REML"        # Method for random-effects model
)

# Extract weights
mace_high_risk_weights <- as.data.frame(paste0(fmtx(weights(ma_mace_high_risk),
                                                         digits = 1), "%")) %>%
  rename(weight = `paste0(fmtx(weights(ma_mace_high_risk), digits = 1), "%")`) %>%
  mutate(weight_num = as.numeric(gsub("%", "", weight)),
         weight_scaled = 0.70 + weight_num * 0.02) #Add numeric weights

#Extract rounded estimate and CI bound
pred_mace_high_risk <- predict(ma_mace_high_risk, transf = exp, digits = 2)
pred_mace_high_risk <- fmtx(c(pred_mace_high_risk$pred,
                              pred_mace_high_risk$ci.lb,
                              pred_mace_high_risk$ci.ub), digits=2)

# Add weights to dataframe
mace_high_risk_data <- cbind(mace_high_risk_data,
                             mace_high_risk_weights)

# Bind dataframes with weights back together
mace_cvd_data <- rbind(mace_high_risk_data, mace_very_high_risk_data)

# Order dataframe
mace_cvd_data <- mace_cvd_data %>%
  arrange(high_risk, desc(weight_num))

# Run meta-analysis by risk of CVD
ma_mace_cvd <- rma(
  measure = "RR",   # Risk Ratio
  ai = mace_events_exp,  # Events in experimental group
  n1i = mace_n_exp,      # Total in experimental group
  ci = mace_events_cont, # Events in control group
  n2i = mace_n_cont,     # Total in control group
  slab = study,          # Study labels
  data = mace_cvd_data,      # Data frame
  method = "REML"        # Method for random-effects model
)

mace_cvd_weights <- as.data.frame(paste0(fmtx(weights(ma_mace_cvd),
                                                    digits = 1), "%")) %>%
  rename(weight_cvd = `paste0(fmtx(weights(ma_mace_cvd), digits = 1), "%")`) %>%
  mutate(weight_num_cvd = as.numeric(gsub("%", "", weight_cvd)),
         weight_scaled_cvd = 0.70 + weight_num_cvd * 0.02) #Add numeric weights

#Extract rounded estimate and CI bound
pred_mace_cvd <- predict(ma_mace_cvd, transf = exp, digits = 2)
pred_mace_cvd <- fmtx(c(pred_mace_cvd$pred,
                        pred_mace_cvd$ci.lb,
                        pred_mace_cvd$ci.ub), digits=2)

# Add weights
mace_cvd_data <- cbind(mace_cvd_data, mace_cvd_weights)

# Rerun meta-analysis by risk of CVD
ma_mace_cvd <- rma(
  measure = "RR",   # Risk Ratio
  ai = mace_events_exp,  # Events in experimental group
  n1i = mace_n_exp,      # Total in experimental group
  ci = mace_events_cont, # Events in control group
  n2i = mace_n_cont,     # Total in control group
  slab = study,          # Study labels
  data = mace_cvd_data,      # Data frame
  method = "REML"        # Method for random-effects model
)

par(mar = c(10, 5, 1.3, 5), mgp = c(3, 1, 0), tcl = -0.2)

# Set up PNG for forest plot for MACE by history of CVD, CKD, HF
png("supp_fig_3.png", width = 16000, height = 8000, res = 1200)

fp_mace_cvd <- forest(ma_mace_cvd,
                      xlim=c(-10, 4),
                      at=log(c(0.1, 0.5, 1, 2, 10)),
                      atransf=exp,
                      order = high_risk,
                      xlab = "",
                      lty = c(1, 1, 0),
                      ilab = cbind(mace_events_exp, mace_n_exp, 
                                   mace_events_cont, mace_n_cont,
                                   mace_cvd_weights$weight_cvd),
                      ilab.xpos=c(-7, -6, -5, -4, -3),
                      cex=0.80,
                      ylim=c(-1, 26),
                      rows = c(5:10, 17:22),
                      mlab = "",
                      psize = weight_scaled_cvd,
                      header = c("Study", "Risk ratio [95% CI]"),
                      showweights = FALSE,
                      addfit = TRUE)

# Add pooled effect of studies with and without patients with CVD
addpoly(ma_mace_very_high_risk, row = 15, cex = 0.80)
addpoly(ma_mace_high_risk, row = 3, cex = 0.80)
addpoly(ma_mace_cvd, row = -1, cex = 0.80)

# hide non-bold summary estimates and study labels
rect(-10, 23, -7.25, -3, col = "White", border = NA)

# Hide point estimates RE
rect(2, c(16, 4, 0),
     4, c(14, 2, -2), col = "White", border = NA)

# Place summary estimates back in bold
text(fp_mace_cvd$textpos[2], -1,
     paste0(pred_mace_cvd[1], " [", pred_mace_cvd[2], ",  ",
            pred_mace_cvd[3], "]"),
     pos=2, font = 2, cex = 0.80)

text(fp_mace_cvd$textpos[2], 15,
     paste0(pred_mace_very_high_risk[1], " [", pred_mace_very_high_risk[2], ",  ",
            pred_mace_very_high_risk[3], "]"),
     pos=2, font = 2, cex = 0.80)

text(fp_mace_cvd$textpos[2], 3,
     paste0(pred_mace_high_risk[1], " [", pred_mace_high_risk[2], ",  ",
            pred_mace_high_risk[3], "]"),
     pos=2, font = 2, cex = 0.80)

# Add horizontal line at the top
segments(-10, 24, 4, 24, lwd = 0.8)

# Expand margins
par(xpd = NA)

# Add labels on top
text(c(-7, -6, -5, -4, -3), 25,
     c("Events", "Total", "Events", "Total", "Weight"), cex = 0.80,
     font = 2)
text(c(-6.5, -4.5, 0), 26,
     c("Combination therapy", "Monotherapy", "Risk ratio"),
     cex = 0.80, font = 2)
text(0, 25, c("MH Random, 95% CI"), cex = 0.80, font = 2)

# Add outcome labels
text(c(-10), c(23, 11), c("History of CVD, CKD, or heart failure",
                          "No history of CVD, CKD, or heart failure"),
     pos = 4, font = 2, cex = 0.80)

# Add study labels
text(-10, c(5:10, 17:22),
     c("Jhu et al (2024) [33]", "Dave et al (2021) [30]",
       "Jensen et al (2020) [32]", "Lau et al (2022) [35]",
       "Simms-Williams et al (2024b) [42]", "Simms-Williams et al (2024a) [43]",
       "Chaiyakunapruk et al (2025) [29]", "Lopez et al (2022) [37]",
       "Simms-Williams et al (2024b) [43]", "Simms-Williams et al (2024a) [43]", 
       "Marfella et al (2024) [39]"),
     cex = 0.80, pos = 4)

# Add Total labels:
text(-10, -1, pos = 4, "Total (95% CI)", font = 2, cex = 0.80)

# Add subtotal labels
text(-10, c(3, 15), "Subtotal (95% CI)", font = 2, cex = 0.80, pos = 4)

#Add text for total events
text(c(-6, -4), -1, c(sum(mace_cvd_data$mace_n_exp),
                      sum(mace_cvd_data$mace_n_cont)),
     font = 2, cex = 0.80)

text(c(-7, -5), -1, c(sum(mace_cvd_data$mace_events_exp),
                      sum(mace_cvd_data$mace_events_cont)),
     cex = 0.80)

# Add text for subtotal events
text(c(-6, -4), 15, c(sum(mace_very_high_risk_data$mace_n_exp),
                      sum(mace_very_high_risk_data$mace_n_cont)), font = 2,
     cex = 0.80)

text(c(-7, -5), 15, c(sum(mace_very_high_risk_data$mace_events_exp),
                      sum(mace_very_high_risk_data$mace_events_cont)),
     cex = 0.80)

text(c(-6, -4), 3, c(sum(mace_high_risk_data$mace_n_exp),
                     sum(mace_high_risk_data$mace_n_cont)), font = 2,
     cex = 0.80)

text(c(-7, -5), 3, c(sum(mace_high_risk_data$mace_events_exp),
                     sum(mace_high_risk_data$mace_events_cont)),
     cex = 0.80)

# Calculate sum of weights for observational studies
mace_cvd_data %>%
  group_by(high_risk) %>%
  summarise(sum_weight = sum(weight_num_cvd))

# Add sum of weights
text(-3, c(15, 3, -1), c("50.2%", "49.8%", "100%"), cex = 0.80, font = 2)

# Extract p-values
p_very_high_het <- fmtp(ma_mace_very_high_risk$QEp, digits = 2, pname = "",
                        add0 = TRUE, sep = TRUE, equal = TRUE)
p_high_het      <- fmtp(ma_mace_high_risk$QEp, digits = 2, pname = "",
                        add0 = TRUE, sep = TRUE, equal = TRUE)
p_pooled_het_hr    <- fmtp(ma_mace_cvd$QEp, digits = 2, pname = "", add0 = TRUE,
                           sep = TRUE, equal = TRUE)

p_very_high_oe  <- fmtp(ma_mace_very_high_risk$pval, digits = 2, pname = "",
                        add0 = TRUE, sep = TRUE, equal = TRUE)
p_high_oe       <- fmtp(ma_mace_high_risk$pval, digits = 2, pname = "",
                        add0 = TRUE, sep = TRUE, equal = TRUE)
p_pooled_oe_hr     <- fmtp(ma_mace_cvd$pval, digits = 2, pname = "",
                           add0 = TRUE, sep = TRUE, equal = TRUE)

# Subgroup difference p-value
p_subgroup_diff_hr <- fmtp(0.10, digits = 2, pname = "", add0 = TRUE,
                           sep = TRUE, equal = TRUE)

# Heterogeneity statistics
# History of CVD, CKD or HF
text(-10, 14, pos = 4, cex = 0.80,
     bquote(paste("Heterogeneity: ",
                  "Tau"^2, " = ", .(fmtx(ma_mace_very_high_risk$tau2, digits = 2)), "; ",
                  "Chi"^2, " = ", .(fmtx(ma_mace_very_high_risk$QE, digits = 2)),
                  ", df = ", .(ma_mace_very_high_risk$k - ma_mace_very_high_risk$p),
                  " (", italic(p), .(p_very_high_het), "); ",
                  I^2, " = ", .(round(ma_mace_very_high_risk$I2)), "%")))

# No history of CVD, CKD or HF
text(-10, 2, pos = 4, cex = 0.80,
     bquote(paste("Heterogeneity: ",
                  "Tau"^2, " = ", .(fmtx(ma_mace_high_risk$tau2, digits = 2)), "; ",
                  "Chi"^2, " = ", .(fmtx(ma_mace_high_risk$QE, digits = 2)),
                  ", df = ", .(ma_mace_high_risk$k - ma_mace_high_risk$p),
                  " (", italic(p), .(p_high_het), "); ",
                  I^2, " = ", .(round(ma_mace_high_risk$I2)), "%")))

# Pooled
text(-10, -2, pos = 4, cex = 0.80,
     bquote(paste("Heterogeneity: ",
                  "Tau"^2, " = ", .(fmtx(ma_mace_cvd$tau2, digits = 2)), "; ",
                  "Chi"^2, " = ", .(fmtx(ma_mace_cvd$QE, digits = 2)),
                  ", df = ", .(ma_mace_cvd$k - ma_mace_cvd$p),
                  " (", italic(p), .(p_pooled_het_hr), "); ",
                  I^2, " = ", .(round(ma_mace_cvd$I2)), "%")))

# Overall effect
# History of CVD, CKD or HF
text(-10, 13, pos = 4, cex = 0.80,
     bquote(paste("Test for overall effect: ",
                  "Z = ", .(fmtx(ma_mace_very_high_risk$zval, digits = 2)),
                  " (", italic(p), .(p_very_high_oe), ")")))

# No history of CVD, CKD or HF
text(-10, 1, pos = 4, cex = 0.80,
     bquote(paste("Test for overall effect: ",
                  "Z = ", .(fmtx(ma_mace_high_risk$zval, digits = 2)),
                  " (", italic(p), .(p_high_oe), ")")))

# Pooled
text(-10, -3, pos = 4, cex = 0.80,
     bquote(paste("Test for overall effect: ",
                  "Z = ", .(fmtx(ma_mace_cvd$zval, digits = 2)),
                  " (", italic(p), .(p_pooled_oe_hr), ")")))

# Determine Q values 
rma(
  measure = "RR",   # Risk Ratio
  ai = mace_events_exp,  # Events in experimental group
  n1i = mace_n_exp,      # Total in experimental group
  ci = mace_events_cont, # Events in control group
  n2i = mace_n_cont,     # Total in control group
  slab = study,          # Study labels
  data = mace_cvd_data,      # Data frame
  method = "REML",        # Method for random-effects model
  mod = high_risk
)

# Subgroup differences
text(-10, -4, pos = 4, cex = 0.80,
     bquote(paste("Test for subgroup differences: ",
                  "Chi"^2, " = ", .(fmtx(2.66, digits = 2)),
                  ", df = ", 1,
                  " (", italic(p), .(p_subgroup_diff_hr), ")")))

# Add label for axes
text(log(c(0.1, 10)), -5, c("Favours combination of SGLT-2 inhibitor and GLP-1 RA",
                            "Favours SGLT-2 inhibitor or GLP-1 RA monotherapy"),
     pos = c(4,2), offset = -7, cex = 0.80)

# Close PNG device
dev.off()

########################## Subgroup by baseline HbA1c ########################## 

# Filter studies with baseline HbA1c
mace_data_hba1c <- mace_data %>%
  filter(!is.na(hba1c)) %>%
  mutate(hba1c_cat = ifelse(hba1c >8, "HbA1c >8%", "HbA1c ≤8"),
         hba1c_num = ifelse(hba1c_cat == "HbA1c >8%", 1, 0))

# Filter studies with high baseline HbA1c
mace_data_hba1c_h <- mace_data_hba1c %>%
  filter(hba1c >8) %>%
  select(study,hba1c_cat, hba1c_num, mace_events_exp, mace_n_exp,
         mace_events_cont, mace_n_cont)

# Run meta-analysis for patients with high HbA1c
ma_mace_hba1c_h <- rma(
  measure = "RR",   # Risk Ratio
  ai = mace_events_exp,  # Events in experimental group
  n1i = mace_n_exp,      # Total in experimental group
  ci = mace_events_cont, # Events in control group
  n2i = mace_n_cont,     # Total in control group
  slab = study,          # Study labels
  data = mace_data_hba1c_h,      # Data frame
  method = "REML"        # Method for random-effects model
)

# Extract weights
mace_hba1c_h_weights <- as.data.frame(paste0(fmtx(weights(ma_mace_hba1c_h),
                                                    digits = 1), "%")) %>%
  rename(weight = `paste0(fmtx(weights(ma_mace_hba1c_h), digits = 1), "%")`) %>%
  mutate(weight_num = as.numeric(gsub("%", "", weight)),
         weight_scaled = 0.7 + weight_num * 0.02) #Add numeric weights

#Extract rounded estimate and CI bound
pred_mace_hba1c_h <- predict(ma_mace_hba1c_h, transf = exp, digits = 2)
pred_mace_hba1c_h <- fmtx(c(pred_mace_hba1c_h$pred,
                            pred_mace_hba1c_h$ci.lb,
                            pred_mace_hba1c_h$ci.ub), digits=2)

# Add weights to dataframe
mace_data_hba1c_h <- cbind(mace_data_hba1c_h,
                           mace_hba1c_h_weights)

# Filter studies with low baseline HbA1c
mace_data_hba1c_l <- mace_data_hba1c %>%
  filter(hba1c <= 8) %>%
  select(study,hba1c_cat, hba1c_num, mace_events_exp, mace_n_exp,
         mace_events_cont, mace_n_cont)

# Run meta-analysis for patients with low HbA1c
ma_mace_hba1c_l <- rma(
  measure = "RR",   # Risk Ratio
  ai = mace_events_exp,  # Events in experimental group
  n1i = mace_n_exp,      # Total in experimental group
  ci = mace_events_cont, # Events in control group
  n2i = mace_n_cont,     # Total in control group
  slab = study,          # Study labels
  data = mace_data_hba1c_l,      # Data frame
  method = "REML"        # Method for random-effects model
)

# Extract weights
mace_hba1c_l_weights <- as.data.frame(paste0(fmtx(weights(ma_mace_hba1c_l),
                                                  digits = 1), "%")) %>%
  rename(weight = `paste0(fmtx(weights(ma_mace_hba1c_l), digits = 1), "%")`) %>%
  mutate(weight_num = as.numeric(gsub("%", "", weight)),
         weight_scaled = 0.7 + weight_num * 0.02) #Add numeric weights

#Extract rounded estimate and CI bound
pred_mace_hba1c_l <- predict(ma_mace_hba1c_l, transf = exp, digits = 2)
pred_mace_hba1c_l <- fmtx(c(pred_mace_hba1c_l$pred,
                            pred_mace_hba1c_l$ci.lb,
                            pred_mace_hba1c_l$ci.ub), digits=2)

# Add weights to dataframe
mace_data_hba1c_l <- cbind(mace_data_hba1c_l,
                           mace_hba1c_l_weights)

# Bind dataframes with weights back together
mace_data_hba1c <- rbind(mace_data_hba1c_h, mace_data_hba1c_l)

# Order dataframe by subgroup and weights
# Order dataframe
mace_data_hba1c <- mace_data_hba1c %>%
  arrange(hba1c_num, desc(weight_num))

# Run meta-analysis for stratified for baseline HbA1c
ma_mace_hba1c <- rma(
  measure = "RR",   # Risk Ratio
  ai = mace_events_exp,  # Events in experimental group
  n1i = mace_n_exp,      # Total in experimental group
  ci = mace_events_cont, # Events in control group
  n2i = mace_n_cont,     # Total in control group
  slab = study,          # Study labels
  data = mace_data_hba1c,      # Data frame
  method = "REML"        # Method for random-effects model
)

#Extract rounded estimate and CI bound
pred_mace_hba1c <- predict(ma_mace_hba1c, transf = exp, digits = 2)
pred_mace_hba1c <- fmtx(c(pred_mace_hba1c$pred,
                            pred_mace_hba1c$ci.lb,
                            pred_mace_hba1c$ci.ub), digits=2)

# Extract weights
mace_hba1c_weights <- as.data.frame(paste0(fmtx(weights(ma_mace_hba1c),
                                                  digits = 1), "%")) %>%
  rename(weight_hba1c = `paste0(fmtx(weights(ma_mace_hba1c), digits = 1), "%")`) %>%
  mutate(weight_num_hba1c = as.numeric(gsub("%", "", weight_hba1c)),
         weight_scaled_hba1c = 0.70 + weight_num_hba1c * 0.02) #Add numeric weights

# Add weights to dataframe
mace_data_hba1c <- cbind(mace_data_hba1c,
                           mace_hba1c_weights)

# Rerun meta-analysis stratified for baseline HbA1c
ma_mace_hba1c <- rma(
  measure = "RR",   # Risk Ratio
  ai = mace_events_exp,  # Events in experimental group
  n1i = mace_n_exp,      # Total in experimental group
  ci = mace_events_cont, # Events in control group
  n2i = mace_n_cont,     # Total in control group
  slab = study,          # Study labels
  data = mace_data_hba1c,      # Data frame
  method = "REML"        # Method for random-effects model
)

# Set up PNG for forest plot for MACE by baseline HbA1c
png("supp_fig_4.png", width = 16000, height = 7000, res = 1200)

fp_mace_hba1c <- forest(ma_mace_hba1c,
                      xlim=c(-10, 4),
                      at=log(c(0.1, 0.5, 1, 2, 10)),
                      atransf=exp,
                      order = hba1c_num,
                      xlab = "",
                      lty = c(1, 1, 0),
                      ilab = cbind(mace_events_exp, mace_n_exp, 
                                   mace_events_cont, mace_n_cont,
                                   weight_hba1c),
                      ilab.xpos=c(-7, -6, -5, -4, -3),
                      cex=0.80,
                      ylim=c(-1, 23),
                      rows = c(5:8, 15:19),
                      mlab = "",
                      psize = weight_scaled_hba1c,
                      header = c("Study", "Risk ratio [95% CI]"),
                      showweights = FALSE,
                      addfit = TRUE)

# Add pooled estimates of studies with and without high baseline HbA1c
addpoly(ma_mace_hba1c_h, row = 13, cex = 0.80)
addpoly(ma_mace_hba1c_l, row = 3, cex = 0.80)

# hide non-bold summary estimates
rect(-10, c(14, 4), -7.25, c(12, 2), col = "White", border = NA)

# Hide point estimates RE
rect(2.5, c(14, 4),
     4, c(12, -4), col = "White", border = NA)

# Place summary estimates back in bold
text(fp_mace_hba1c$textpos[2], -1,
     paste0(pred_mace_hba1c[1], " [", pred_mace_hba1c[2], ",  ",
            pred_mace_hba1c[3], "]"),
     pos=2, font = 2, cex = 0.80)

text(fp_mace_hba1c$textpos[2], 13,
     paste0(pred_mace_hba1c_h[1], " [", pred_mace_hba1c_h[2], ",  ",
            pred_mace_hba1c_h[3], "]"),
     pos=2, font = 2, cex = 0.80)

text(fp_mace_hba1c$textpos[2], 3,
     paste0(pred_mace_hba1c_l[1], " [", pred_mace_hba1c_l[2], ",  ",
            pred_mace_hba1c_l[3], "]"),
     pos=2, font = 2, cex = 0.80)

# Add horizontal line at the top
segments(-10, 21, 4, 21, lwd = 0.8)

# Expand margins
par(xpd = NA)

# Add labels on top
text(c(-7, -6, -5, -4, -3), 22,
     c("Events", "Total", "Events", "Total", "Weight"), cex = 0.80,
     font = 2)
text(c(-6.5, -4.5, 0), 23,
     c("Combination therapy", "Monotherapy", "Risk ratio"),
     cex = 0.80, font = 2)
text(0, 22, c("MH Random, 95% CI"), cex = 0.80, font = 2)

# Add outcome labels
text(c(-10), c(20, 9), c("Baseline HbA1c >64 mmol/mol", "Baseline HbA1c ≤64 mmol/mol"),
     pos = 4, font = 2, cex = 0.80)

# Add Total labels:
text(-10, -1, pos = 4, "Total (95% CI)", font = 2, cex = 0.80)

# Add subtotal labels
text(-10, c(3, 13), "Subtotal (95% CI)", font = 2, cex = 0.80, pos = 4)

#Add text for total events
text(c(-6, -4), -1, c(sum(mace_data_hba1c$mace_n_exp),
                      sum(mace_data_hba1c$mace_n_cont)),
     font = 2, cex = 0.80)

text(c(-7, -5), -1, c(sum(mace_data_hba1c$mace_events_exp),
                      sum(mace_data_hba1c$mace_events_cont)),
     cex = 0.80)

# Add text for subtotal events
text(c(-6, -4), 13, c(sum(mace_data_hba1c_h$mace_n_exp),
                      sum(mace_data_hba1c_h$mace_n_cont)), font = 2,
     cex = 0.80)

text(c(-7, -5), 13, c(sum(mace_data_hba1c_h$mace_events_exp),
                      sum(mace_data_hba1c_h$mace_events_cont)),
     cex = 0.80)

text(c(-6, -4), 3, c(sum(mace_data_hba1c_l$mace_n_exp),
                     sum(mace_data_hba1c_l$mace_n_cont)), font = 2,
     cex = 0.80)

text(c(-7, -5), 3, c(sum(mace_data_hba1c_l$mace_events_exp),
                     sum(mace_data_hba1c_l$mace_events_cont)),
     cex = 0.80)

# Calculate sum of weights for studies with an HbA1c > and =< 8%
mace_data_hba1c %>%
  group_by(hba1c_cat) %>%
  summarise(sum_weight = sum(weight_num_hba1c))

# Add sum of weights
text(-3, c(13, 3, -1), c("56.6%", "43.4%", "100%"), cex = 0.80, font = 2)

# Extract p-values
p_hba1c_h_het <- fmtp(ma_mace_hba1c_h$QEp, digits = 2, pname = "", add0 = TRUE,
                      sep = TRUE, equal = TRUE)
p_hba1c_l_het <- fmtp(ma_mace_hba1c_l$QEp, digits = 2, pname = "", add0 = TRUE,
                      sep = TRUE, equal = TRUE)
p_hba1c_pooled_het <- fmtp(ma_mace_hba1c$QEp, digits = 2, pname = "",
                           add0 = TRUE, sep = TRUE, equal = TRUE)

p_hba1c_h_oe <- fmtp(ma_mace_hba1c_h$pval, digits = 2, pname = "", add0 = TRUE,
                     sep = TRUE, equal = TRUE)
p_hba1c_l_oe <- fmtp(ma_mace_hba1c_l$pval, digits = 2, pname = "", add0 = TRUE,
                     sep = TRUE, equal = TRUE)
p_hba1c_pooled_oe <- fmtp(ma_mace_hba1c$pval, digits = 2, pname = "",
                          add0 = TRUE, sep = TRUE, equal = TRUE)

# Subgroup difference p-value
p_subgroup_diff_hba1c <- fmtp(0.30, digits = 2, pname = "", add0 = TRUE,
                              sep = TRUE, equal = TRUE)

# Heterogeneity statistics
# High HbA1c
text(-10, 12, pos = 4, cex = 0.80,
     bquote(paste("Heterogeneity: ",
                  "Tau"^2, " = ", .(fmtx(ma_mace_hba1c_h$tau2, digits = 2)), "; ",
                  "Chi"^2, " = ", .(fmtx(ma_mace_hba1c_h$QE, digits = 2)),
                  ", df = ", .(ma_mace_hba1c_h$k - ma_mace_hba1c_h$p),
                  " (", italic(p), .(p_hba1c_h_het), "); ",
                  I^2, " = ", .(round(ma_mace_hba1c_h$I2)), "%")))

# Low HbA1c
text(-10, 2, pos = 4, cex = 0.80,
     bquote(paste("Heterogeneity: ",
                  "Tau"^2, " = ", .(fmtx(ma_mace_hba1c_l$tau2, digits = 2)), "; ",
                  "Chi"^2, " = ", .(fmtx(ma_mace_hba1c_l$QE, digits = 2)),
                  ", df = ", .(ma_mace_hba1c_l$k - ma_mace_hba1c_l$p),
                  " (", italic(p), .(p_hba1c_l_het), "); ",
                  I^2, " = ", .(round(ma_mace_hba1c_l$I2)), "%")))

# Pooled
text(-10, -2, pos = 4, cex = 0.80,
     bquote(paste("Heterogeneity: ",
                  "Tau"^2, " = ", .(fmtx(ma_mace_hba1c$tau2, digits = 2)), "; ",
                  "Chi"^2, " = ", .(fmtx(ma_mace_hba1c$QE, digits = 2)),
                  ", df = ", .(ma_mace_hba1c$k - ma_mace_hba1c$p),
                  " (", italic(p), .(p_hba1c_pooled_het), "); ",
                  I^2, " = ", .(round(ma_mace_hba1c$I2)), "%")))

# Overall effect
# High HbA1c
text(-10, 11, pos = 4, cex = 0.80,
     bquote(paste("Test for overall effect: ",
                  "Z = ", .(fmtx(ma_mace_hba1c_h$zval, digits = 2)),
                  " (", italic(p), .(p_hba1c_h_oe), ")")))

# Low HbA1c
text(-10, 1, pos = 4, cex = 0.80,
     bquote(paste("Test for overall effect: ",
                  "Z = ", .(fmtx(ma_mace_hba1c_l$zval, digits = 2)),
                  " (", italic(p), .(p_hba1c_l_oe), ")")))

# Pooled
text(-10, -3, pos = 4, cex = 0.80,
     bquote(paste("Test for overall effect: ",
                  "Z = ", .(fmtx(ma_mace_hba1c$zval, digits = 2)),
                  " (", italic(p), .(p_hba1c_pooled_oe), ")")))

# Determine subgroup differences
rma(
  measure = "RR",   # Risk Ratio
  ai = mace_events_exp,  # Events in experimental group
  n1i = mace_n_exp,      # Total in experimental group
  ci = mace_events_cont, # Events in control group
  n2i = mace_n_cont,     # Total in control group
  slab = study,          # Study labels
  data = mace_data_hba1c,      # Data frame
  method = "REML",        # Method for random-effects model
  mod = hba1c_num
)

# Subgroup differences
text(-10, -4, pos = 4, cex = 0.80,
     bquote(paste("Test for subgroup differences: ",
                  "Chi"^2, " = ", .(fmtx(1.09, digits = 2)),
                  ", df = ", 1,
                  " (", italic(p), .(p_subgroup_diff_hba1c), ")")))

# Add label for axes
text(log(c(0.1, 10)), -5, c("Favours combination of SGLT-2 inhibitor and GLP-1 RA",
                            "Favours SGLT-2 inhibitor or GLP-1 RA monotherapy"),
     pos = c(4,2), offset = -7, cex = 0.80)

# Close PNG device
dev.off()

######################### Subgroup by diabetes duration ######################## 

# Filter studies with diabetes duration
mace_data_dm_years <- mace_data %>%
  filter(!is.na(dm_years)) %>%
  mutate(dm_years_cat = ifelse(dm_years >10, "Diabetes duration > 10 years",
                               "Diabetes duration ≤10 years"),
         dm_years_num = ifelse(dm_years_cat == "Diabetes duration > 10 years",
                               1, 0))

# Filter studies with long diabetes duration
mace_data_dm_years_l <- mace_data_dm_years %>%
  filter(dm_years >10) %>%
  select(study,dm_years_cat, dm_years_num, mace_events_exp, mace_n_exp,
         mace_events_cont, mace_n_cont)

# Run meta-analysis for patients with long diabetes duration
ma_mace_dm_years_l <- rma(
  measure = "RR",   # Risk Ratio
  ai = mace_events_exp,  # Events in experimental group
  n1i = mace_n_exp,      # Total in experimental group
  ci = mace_events_cont, # Events in control group
  n2i = mace_n_cont,     # Total in control group
  slab = study,          # Study labels
  data = mace_data_dm_years_l,      # Data frame
  method = "REML"        # Method for random-effects model
)

# Extract weights
mace_dm_years_l_weights <- as.data.frame(paste0(fmtx(weights(ma_mace_dm_years_l),
                                                  digits = 1), "%")) %>%
  rename(weight = `paste0(fmtx(weights(ma_mace_dm_years_l), digits = 1), "%")`) %>%
  mutate(weight_num = as.numeric(gsub("%", "", weight)),
         weight_scaled = 0.7 + weight_num * 0.02) #Add numeric weights

#Extract rounded estimate and CI bound
pred_mace_dm_years_l <- predict(ma_mace_dm_years_l, transf = exp, digits = 2)
pred_mace_dm_years_l <- fmtx(c(pred_mace_dm_years_l$pred,
                               pred_mace_dm_years_l$ci.lb,
                               pred_mace_dm_years_l$ci.ub), digits=2)

# Add weights to dataframe
mace_data_dm_years_l <- cbind(mace_data_dm_years_l,
                           mace_dm_years_l_weights)

# Filter studies with short diabetes duration
mace_data_dm_years_s <- mace_data_dm_years %>%
  filter(dm_years <=10) %>%
  select(study,dm_years_cat, dm_years_num, mace_events_exp, mace_n_exp,
         mace_events_cont, mace_n_cont)

# Run meta-analysis for patients with short diabetes duration
ma_mace_dm_years_s <- rma(
  measure = "RR",   # Risk Ratio
  ai = mace_events_exp,  # Events in experimental group
  n1i = mace_n_exp,      # Total in experimental group
  ci = mace_events_cont, # Events in control group
  n2i = mace_n_cont,     # Total in control group
  slab = study,          # Study labels
  data = mace_data_dm_years_s,      # Data frame
  method = "REML"        # Method for random-effects model
)

# Extract weights
mace_dm_years_s_weights <- as.data.frame(paste0(fmtx(weights(ma_mace_dm_years_s),
                                                     digits = 1), "%")) %>%
  rename(weight = `paste0(fmtx(weights(ma_mace_dm_years_s), digits = 1), "%")`) %>%
  mutate(weight_num = as.numeric(gsub("%", "", weight)),
         weight_scaled = 0.7 + weight_num * 0.02) #Add numeric weights

#Extract rounded estimate and CI bound
pred_mace_dm_years_s <- predict(ma_mace_dm_years_s, transf = exp, digits = 2)
pred_mace_dm_years_s <- fmtx(c(pred_mace_dm_years_s$pred,
                               pred_mace_dm_years_s$ci.lb,
                               pred_mace_dm_years_s$ci.ub), digits=2)

# Rerun meta-analysis stratified for baseline HbA1c
ma_mace_dm_years <- rma(
  measure = "RR",   # Risk Ratio
  ai = mace_events_exp,  # Events in experimental group
  n1i = mace_n_exp,      # Total in experimental group
  ci = mace_events_cont, # Events in control group
  n2i = mace_n_cont,     # Total in control group
  slab = study,          # Study labels
  data = mace_data_dm_years,      # Data frame
  method = "REML"        # Method for random-effects model
)

# Extract weights
mace_dm_years_weights <- as.data.frame(paste0(fmtx(weights(ma_mace_dm_years),
                                                digits = 1), "%")) %>%
  rename(weight_dm_years = `paste0(fmtx(weights(ma_mace_dm_years), digits = 1), "%")`) %>%
  mutate(weight_num_dm_years = as.numeric(gsub("%", "", weight_dm_years)),
         weight_scaled_dm_years = 0.70 + weight_num_dm_years * 0.02) #Add numeric weights

# Add weights to dataframe
mace_data_dm_years <- cbind(mace_data_dm_years,
                         mace_dm_years_weights)

mace_data_dm_years <- mace_data_dm_years %>%
  arrange(dm_years_cat, desc(weight_num_dm_years))


# Rerun meta-analysis stratified for diabetes duration
ma_mace_dm_years <- rma(
  measure = "RR",   # Risk Ratio
  ai = mace_events_exp,  # Events in experimental group
  n1i = mace_n_exp,      # Total in experimental group
  ci = mace_events_cont, # Events in control group
  n2i = mace_n_cont,     # Total in control group
  slab = study,          # Study labels
  data = mace_data_dm_years,      # Data frame
  method = "REML"        # Method for random-effects model
)

#Extract rounded estimate and CI bound
pred_mace_dm_years <- predict(ma_mace_dm_years, transf = exp, digits = 2)
pred_mace_dm_years <- fmtx(c(pred_mace_dm_years$pred,
                               pred_mace_dm_years$ci.lb,
                               pred_mace_dm_years$ci.ub), digits=2)

# Set up PNG for forest plot for MACE by baseline HbA1c
png("supp_fig_5.png", width = 16000, height = 7000, res = 1200)

fp_mace_dm_years <- forest(ma_mace_dm_years,
                        xlim=c(-10, 4),
                        at=log(c(0.1, 0.5, 1, 2, 10)),
                        atransf=exp,
                        order = dm_years_num,
                        xlab = "",
                        lty = c(1, 1, 0),
                        ilab = cbind(mace_events_exp, mace_n_exp, 
                                     mace_events_cont, mace_n_cont,
                                     weight_dm_years),
                        ilab.xpos=c(-7, -6, -5, -4, -3),
                        cex=0.80,
                        ylim=c(-1, 20),
                        rows = c(5:7, 14:16),
                        mlab = "",
                        psize = weight_scaled_dm_years,
                        header = c("Study", "Risk ratio [95% CI]"),
                        showweights = FALSE,
                        addfit = TRUE)

# Add pooled estimates of studies with and without high baseline HbA1c
addpoly(ma_mace_dm_years_l, row = 12, cex = 0.80)
addpoly(ma_mace_dm_years_s, row = 3, cex = 0.80)

# hide non-bold summary estimates
rect(-10, c(13, 4), -7.25, c(11, 2), col = "White", border = NA)

# Hide point estimates RE
rect(2.5, c(13, 4),
     4, c(11, -4), col = "White", border = NA)

# Place summary estimates back in bold
text(fp_mace_dm_years$textpos[2], -1,
     paste0(pred_mace_dm_years[1], " [", pred_mace_dm_years[2], ",  ",
            pred_mace_dm_years[3], "]"),
     pos=2, font = 2, cex = 0.80)

text(fp_mace_dm_years$textpos[2], 12,
     paste0(pred_mace_dm_years_l[1], " [", pred_mace_dm_years_l[2], ",  ",
            pred_mace_dm_years_l[3], "]"),
     pos=2, font = 2, cex = 0.80)

text(fp_mace_dm_years$textpos[2], 3,
     paste0(pred_mace_dm_years_s[1], " [", pred_mace_dm_years_s[2], ",  ",
            pred_mace_dm_years_s[3], "]"),
     pos=2, font = 2, cex = 0.80)

# Add horizontal line at the top
segments(-10, 18, 4, 18, lwd = 0.8)

# Expand margins
par(xpd = NA)

# Add labels on top
text(c(-7, -6, -5, -4, -3), 19,
     c("Events", "Total", "Events", "Total", "Weight"), cex = 0.80,
     font = 2)
text(c(-6.5, -4.5, 0), 20,
     c("Combination therapy", "Monotherapy", "Risk ratio"),
     cex = 0.80, font = 2)
text(0, 19, c("MH Random, 95% CI"), cex = 0.80, font = 2)

# Add outcome labels
text(c(-10), c(17, 8),
     c("Baseline diabetes duration >10 years",
       "Baseline diabetes duration ≤10 years"),
     pos = 4, font = 2, cex = 0.80)

# Add Total labels:
text(-10, -1, pos = 4, "Total (95% CI)", font = 2, cex = 0.80)

# Add subtotal labels
text(-10, c(3, 12), "Subtotal (95% CI)", font = 2, cex = 0.80, pos = 4)

#Add text for total events
text(c(-6, -4), -1, c(sum(mace_data_dm_years$mace_n_exp),
                      sum(mace_data_dm_years$mace_n_cont)),
     font = 2, cex = 0.80)

text(c(-7, -5), -1, c(sum(mace_data_dm_years$mace_events_exp),
                      sum(mace_data_dm_years$mace_events_cont)),
     cex = 0.80)

# Add text for subtotal events
text(c(-6, -4), 12, c(sum(mace_data_dm_years_l$mace_n_exp),
                      sum(mace_data_dm_years_l$mace_n_cont)), font = 2,
     cex = 0.80)

text(c(-7, -5), 12, c(sum(mace_data_dm_years_l$mace_events_exp),
                      sum(mace_data_dm_years_l$mace_events_cont)),
     cex = 0.80)

text(c(-6, -4), 3, c(sum(mace_data_dm_years_s$mace_n_exp),
                     sum(mace_data_dm_years_s$mace_n_cont)), font = 2,
     cex = 0.80)

text(c(-7, -5), 3, c(sum(mace_data_dm_years_s$mace_events_exp),
                     sum(mace_data_dm_years_s$mace_events_cont)),
     cex = 0.80)

# Calculate sum of weights for studies with a diabetes duration > and =< 10 years
mace_data_dm_years %>%
  group_by(dm_years_cat) %>%
  summarise(sum_weight = sum(weight_num_dm_years))

# Add sum of weights
text(-3, c(12, 3, -1), c("49.9%", "50.2%", "100%"), cex = 0.80, font = 2)

# Extract p-values
p_dm_long_het   <- fmtp(ma_mace_dm_years_l$QEp, digits = 2, pname = "",
                        add0 = TRUE, sep = TRUE, equal = TRUE)
p_dm_short_het  <- fmtp(ma_mace_dm_years_s$QEp, digits = 2, pname = "",
                        add0 = TRUE, sep = TRUE, equal = TRUE)
p_dm_pooled_het <- fmtp(ma_mace_dm_years$QEp, digits = 2, pname = "",
                        add0 = TRUE, sep = TRUE, equal = TRUE)

p_dm_long_oe    <- fmtp(ma_mace_dm_years_l$pval, digits = 2, pname = "",
                        add0 = TRUE, sep = TRUE, equal = TRUE)
p_dm_short_oe   <- fmtp(ma_mace_dm_years_s$pval, digits = 2, pname = "",
                        add0 = TRUE, sep = TRUE, equal = TRUE)
p_dm_pooled_oe  <- fmtp(ma_mace_dm_years$pval, digits = 2, pname = "",
                        add0 = TRUE, sep = TRUE, equal = TRUE)

# Subgroup difference p-value
p_subgroup_diff_dm <- fmtp(0.01, digits = 2, pname = "", add0 = TRUE,
                           sep = TRUE, equal = TRUE)

# Heterogeneity statistics
# Long diabetes duration
text(-10, 11, pos = 4, cex = 0.80,
     bquote(paste("Heterogeneity: ",
                  "Tau"^2, " = ", .(fmtx(ma_mace_dm_years_l$tau2, digits = 2)), "; ",
                  "Chi"^2, " = ", .(fmtx(ma_mace_dm_years_l$QE, digits = 2)),
                  ", df = ", .(ma_mace_dm_years_l$k - ma_mace_dm_years_l$p),
                  " (", italic(p), .(p_dm_long_het), "); ",
                  I^2, " = ", .(round(ma_mace_dm_years_l$I2)), "%")))

# Short diabetes duration
text(-10, 2, pos = 4, cex = 0.80,
     bquote(paste("Heterogeneity: ",
                  "Tau"^2, " = ", .(fmtx(ma_mace_dm_years_s$tau2, digits = 2)), "; ",
                  "Chi"^2, " = ", .(fmtx(ma_mace_dm_years_s$QE, digits = 2)),
                  ", df = ", .(ma_mace_dm_years_s$k - ma_mace_dm_years_s$p),
                  " (", italic(p), .(p_dm_short_het), "); ",
                  I^2, " = ", .(round(ma_mace_dm_years_s$I2)), "%")))

# Pooled
text(-10, -2, pos = 4, cex = 0.80,
     bquote(paste("Heterogeneity: ",
                  "Tau"^2, " = ", .(fmtx(ma_mace_dm_years$tau2, digits = 2)), "; ",
                  "Chi"^2, " = ", .(fmtx(ma_mace_dm_years$QE, digits = 2)),
                  ", df = ", .(ma_mace_dm_years$k - ma_mace_dm_years$p),
                  " (", italic(p), .(p_dm_pooled_het), "); ",
                  I^2, " = ", .(round(ma_mace_dm_years$I2)), "%")))

# Overall effect
# Long diabetes duration
text(-10, 10, pos = 4, cex = 0.80,
     bquote(paste("Test for overall effect: ",
                  "Z = ", .(fmtx(ma_mace_dm_years_l$zval, digits = 2)),
                  " (", italic(p), .(p_dm_long_oe), ")")))

# Short diabetes duration
text(-10, 1, pos = 4, cex = 0.80,
     bquote(paste("Test for overall effect: ",
                  "Z = ", .(fmtx(ma_mace_dm_years_s$zval, digits = 2)),
                  " (", italic(p), .(p_dm_short_oe), ")")))

# Pooled
text(-10, -3, pos = 4, cex = 0.80,
     bquote(paste("Test for overall effect: ",
                  "Z = ", .(fmtx(ma_mace_dm_years$zval, digits = 2)),
                  " (", italic(p), .(p_dm_pooled_oe), ")")))

# Determine subgroup differences
rma(
  measure = "RR",   # Risk Ratio
  ai = mace_events_exp,  # Events in experimental group
  n1i = mace_n_exp,      # Total in experimental group
  ci = mace_events_cont, # Events in control group
  n2i = mace_n_cont,     # Total in control group
  slab = study,          # Study labels
  data = mace_data_dm_years,      # Data frame
  method = "REML",        # Method for random-effects model
  mod = dm_years_num
)

# Subgroup differences
text(-10, -4, pos = 4, cex = 0.80,
     bquote(paste("Test for subgroup differences: ",
                  "Chi"^2, " = ", .(fmtx(7.67, digits = 2)),
                  ", df = ", 1,
                  " (", italic(p), .(p_subgroup_diff_dm), ")")))

# Add label for axes
text(log(c(0.1, 10)), -5, c("Favours combination of SGLT-2 inhibitor and GLP-1 RA",
                            "Favours SGLT-2 inhibitor or GLP-1 RA monotherapy"),
     pos = c(4,2), offset = -7, cex = 0.80)

# Close PNG device
dev.off()

####################### Subgroup analyses by risk of bias ######################

# Make risk of bias categorical and numeric
mace_data_rob <- mace_data %>%
  mutate(rob_cat = ifelse(rob == "low", "Low",
                          "Moderate/serious/critical"),
         rob_num = ifelse(rob_cat == "Low",
                          1, 0))

# Filter studies with low risk of bias
mace_data_low_rob <- mace_data_rob %>%
  filter(rob_cat == "Low") %>%
  select(study,rob_cat, rob_num, mace_events_exp, mace_n_exp,
         mace_events_cont, mace_n_cont)

# Run meta-analysis for studies with low RoB
ma_mace_low_rob <- rma(
  measure = "RR",   # Risk Ratio
  ai = mace_events_exp,  # Events in experimental group
  n1i = mace_n_exp,      # Total in experimental group
  ci = mace_events_cont, # Events in control group
  n2i = mace_n_cont,     # Total in control group
  slab = study,          # Study labels
  data = mace_data_low_rob,      # Data frame
  method = "REML"        # Method for random-effects model
)

# Extract weights
mace_low_rob_weights <- as.data.frame(paste0(fmtx(weights(ma_mace_low_rob),
                                                  digits = 1), "%")) %>%
  rename(weight = `paste0(fmtx(weights(ma_mace_low_rob), digits = 1), "%")`) %>%
  mutate(weight_num = as.numeric(gsub("%", "", weight)),
         weight_scaled = 0.75 + weight_num * 0.06) #Add numeric weights

#Extract rounded estimate and CI bound
pred_mace_low_rob <- predict(ma_mace_low_rob, transf = exp, digits = 2)
pred_mace_low_rob <- fmtx(c(pred_mace_low_rob$pred,
                            pred_mace_low_rob$ci.lb,
                            pred_mace_low_rob$ci.ub), digits=2)

# Add weights to dataframe
mace_data_low_rob <- cbind(mace_data_low_rob,
                           mace_low_rob_weights)

# Filter studies with high risk of bias
mace_data_high_rob <- mace_data_rob %>%
  filter(rob_cat == "Moderate/serious/critical") %>%
  select(study,rob_cat, rob_num, mace_events_exp, mace_n_exp,
         mace_events_cont, mace_n_cont)

# Run meta-analysis for studies with some concerns/serious/critical RoB
ma_mace_high_rob <- rma(
  measure = "RR",   # Risk Ratio
  ai = mace_events_exp,  # Events in experimental group
  n1i = mace_n_exp,      # Total in experimental group
  ci = mace_events_cont, # Events in control group
  n2i = mace_n_cont,     # Total in control group
  slab = study,          # Study labels
  data = mace_data_high_rob,      # Data frame
  method = "REML"        # Method for random-effects model
)

# Extract weights
mace_high_rob_weights <- as.data.frame(paste0(fmtx(weights(ma_mace_high_rob),
                                                   digits = 1), "%")) %>%
  rename(weight = `paste0(fmtx(weights(ma_mace_high_rob), digits = 1), "%")`) %>%
  mutate(weight_num = as.numeric(gsub("%", "", weight)),
         weight_scaled = 0.70 + weight_num * 0.02) #Add numeric weights

#Extract rounded estimate and CI bound
pred_mace_high_rob <- predict(ma_mace_high_rob, transf = exp, digits = 2)
pred_mace_high_rob <- fmtx(c(pred_mace_high_rob$pred,
                             pred_mace_high_rob$ci.lb,
                             pred_mace_high_rob$ci.ub), digits=2)

# Add weights to dataframe
mace_data_high_rob <- cbind(mace_data_high_rob,
                            mace_high_rob_weights)

# Bind dataframes with weights back together
mace_data_rob <- rbind(mace_data_low_rob, mace_data_high_rob)

# Order dataframe by subgroup and weights
# Order dataframe
mace_data_rob <- mace_data_rob %>%
  arrange(rob_num, desc(weight_num))

# Run meta-analysis for stratified for risk of bias
ma_mace_rob <- rma(
  measure = "RR",   # Risk Ratio
  ai = mace_events_exp,  # Events in experimental group
  n1i = mace_n_exp,      # Total in experimental group
  ci = mace_events_cont, # Events in control group
  n2i = mace_n_cont,     # Total in control group
  slab = study,          # Study labels
  data = mace_data_rob,      # Data frame
  method = "REML"        # Method for random-effects model
)

#Extract rounded estimate and CI bound
pred_mace_rob <- predict(ma_mace_rob, transf = exp, digits = 2)
pred_mace_rob <- fmtx(c(pred_mace_rob$pred,
                        pred_mace_rob$ci.lb,
                        pred_mace_rob$ci.ub), digits=2)

# Extract weights
mace_rob_weights <- as.data.frame(paste0(fmtx(weights(ma_mace_rob),
                                              digits = 1), "%")) %>%
  rename(weight_rob = `paste0(fmtx(weights(ma_mace_rob), digits = 1), "%")`) %>%
  mutate(weight_num_rob = as.numeric(gsub("%", "", weight_rob)),
         weight_scaled_rob = 0.70 + weight_num_rob * 0.02) #Add numeric weights

# Add weights to dataframe
mace_data_rob <- cbind(mace_data_rob,
                       mace_rob_weights)

# Run meta-analysis for stratified for risk of bias
ma_mace_rob <- rma(
  measure = "RR",   # Risk Ratio
  ai = mace_events_exp,  # Events in experimental group
  n1i = mace_n_exp,      # Total in experimental group
  ci = mace_events_cont, # Events in control group
  n2i = mace_n_cont,     # Total in control group
  slab = study,          # Study labels
  data = mace_data_rob,      # Data frame
  method = "REML"        # Method for random-effects model
)

# Set up PNG for forest plot for MACE by risk of bias
png("supp_fig_6.png", width = 16000, height = 8000, res = 1200)

fp_mace_rob <- forest(ma_mace_rob,
                      xlim=c(-10, 4),
                      at=log(c(0.1, 0.5, 1, 2, 10)),
                      atransf=exp,
                      order = rob_num,
                      xlab = "",
                      lty = c(1, 1, 0),
                      ilab = cbind(mace_events_exp, mace_n_exp, 
                                   mace_events_cont, mace_n_cont,
                                   weight_rob),
                      ilab.xpos=c(-7, -6, -5, -4, -3),
                      cex=0.80,
                      ylim=c(-1, 24),
                      rows = c(5:13, 20),
                      mlab = "",
                      psize = weight_scaled_rob,
                      header = c("Study", "Risk ratio [95% CI]"),
                      showweights = FALSE,
                      addfit = TRUE)

# Add pooled estimates of studies with and without high baseline HbA1c
addpoly(ma_mace_low_rob, row = 18, cex = 0.80)
addpoly(ma_mace_high_rob, row = 3, cex = 0.80)

# hide non-bold summary estimates and study labels
rect(-10, c(19, 4), -7.25, c(17, 2), col = "White", border = NA)

# Hide point estimates RE
rect(2.5, c(19, 4),
     4, c(17, -4), col = "White", border = NA)

# Place summary estimates back in bold
text(fp_mace_rob$textpos[2], -1,
     paste0(pred_mace_rob[1], " [", pred_mace_rob[2], ",  ",
            pred_mace_rob[3], "]"),
     pos=2, font = 2, cex = 0.80)

text(fp_mace_rob$textpos[2], 18,
     paste0(pred_mace_low_rob[1], " [", pred_mace_low_rob[2], ",  ",
            pred_mace_low_rob[3], "]"),
     pos=2, font = 2, cex = 0.80)

text(fp_mace_rob$textpos[2], 3,
     paste0(pred_mace_high_rob[1], " [", pred_mace_high_rob[2], ",  ",
            pred_mace_high_rob[3], "]"),
     pos=2, font = 2, cex = 0.80)

# Add horizontal line at the top
segments(-10, 22, 4, 22, lwd = 0.8)

# Expand margins
par(xpd = NA)

# Add labels on top
text(c(-7, -6, -5, -4, -3), 23,
     c("Events", "Total", "Events", "Total", "Weight"), cex = 0.80,
     font = 2)
text(c(-6.5, -4.5, 0), 24,
     c("Combination therapy", "Monotherapy", "Risk ratio"),
     cex = 0.80, font = 2)
text(0, 23, c("MH Random, 95% CI"), cex = 0.80, font = 2)

# Add outcome labels
text(c(-10), c(21, 14),
     c("Low risk of bias",
       "Moderate/serious/critical risk of bias"),
     pos = 4, font = 2, cex = 0.80)

# Add Total labels:
text(-10, -1, pos = 4, "Total (95% CI)", font = 2, cex = 0.80)

# Add subtotal labels
text(-10, c(3, 18), "Subtotal (95% CI)", font = 2, cex = 0.80, pos = 4)

#Add text for total events
text(c(-6, -4), -1, c(sum(mace_data_rob$mace_n_exp),
                      sum(mace_data_rob$mace_n_cont)),
     font = 2, cex = 0.80)

text(c(-7, -5), -1, c(sum(mace_data_rob$mace_events_exp),
                      sum(mace_data_rob$mace_events_cont)),
     cex = 0.80)

# Add text for subtotal events
text(c(-6, -4), 18, c(sum(mace_data_low_rob$mace_n_exp),
                      sum(mace_data_low_rob$mace_n_cont)), font = 2,
     cex = 0.80)

text(c(-7, -5), 18, c(sum(mace_data_low_rob$mace_events_exp),
                      sum(mace_data_low_rob$mace_events_cont)),
     cex = 0.80)

text(c(-6, -4), 3, c(sum(mace_data_high_rob$mace_n_exp),
                     sum(mace_data_high_rob$mace_n_cont)), font = 2,
     cex = 0.80)

text(c(-7, -5), 3, c(sum(mace_data_high_rob$mace_events_exp),
                     sum(mace_data_high_rob$mace_events_cont)),
     cex = 0.80)

# Calculate sum of weights for studies with a low and high risk of bias
mace_data_rob %>%
  group_by(rob_cat) %>%
  summarise(sum_weight = sum(weight_num_rob))

# Add sum of weights
text(-3, c(18, 3, -1), c("8.7%", "91.2%", "100%"), cex = 0.80, font = 2)

# Extract p-values
p_rob_low_het    <- fmtp(ma_mace_low_rob$QEp, digits = 2, pname = "",
                         add0 = TRUE, sep = TRUE, equal = TRUE)
p_rob_high_het   <- fmtp(ma_mace_high_rob$QEp, digits = 2, pname = "",
                         add0 = TRUE, sep = TRUE, equal = TRUE)
p_rob_pooled_het <- fmtp(ma_mace_rob$QEp, digits = 2, pname = "",
                         add0 = TRUE, sep = TRUE, equal = TRUE)

p_rob_low_oe     <- fmtp(ma_mace_low_rob$pval, digits = 2, pname = "",
                         add0 = TRUE, sep = TRUE, equal = TRUE)
p_rob_high_oe    <- fmtp(ma_mace_high_rob$pval, digits = 2, pname = "",
                         add0 = TRUE, sep = TRUE, equal = TRUE)
p_rob_pooled_oe  <- fmtp(ma_mace_rob$pval, digits = 2, pname = "",
                         add0 = TRUE, sep = TRUE, equal = TRUE)

# Subgroup difference p-value
p_subgroup_diff_rob <- fmtp(0.14, digits = 2, pname = "", add0 = TRUE,
                            sep = TRUE, equal = TRUE)

# Heterogeneity statistics
# Low risk of bias
text(-10, 17, pos = 4, cex = 0.80,
     bquote(paste("Heterogeneity: ",
                  "Tau"^2, " = ", .(fmtx(ma_mace_low_rob$tau2, digits = 2)), "; ",
                  "Chi"^2, " = ", .(fmtx(ma_mace_low_rob$QE, digits = 2)),
                  ", df = ", .(ma_mace_low_rob$k - ma_mace_low_rob$p),
                  " (", italic(p), .(p_rob_low_het), "); ",
                  I^2, " = ", .(round(ma_mace_low_rob$I2)), "%")))

# High risk of bias
text(-10, 2, pos = 4, cex = 0.80,
     bquote(paste("Heterogeneity: ",
                  "Tau"^2, " = ", .(fmtx(ma_mace_high_rob$tau2, digits = 2)), "; ",
                  "Chi"^2, " = ", .(fmtx(ma_mace_high_rob$QE, digits = 2)),
                  ", df = ", .(ma_mace_high_rob$k - ma_mace_high_rob$p),
                  " (", italic(p), .(p_rob_high_het), "); ",
                  I^2, " = ", .(round(ma_mace_high_rob$I2)), "%")))

# Pooled
text(-10, -2, pos = 4, cex = 0.80,
     bquote(paste("Heterogeneity: ",
                  "Tau"^2, " = ", .(fmtx(ma_mace_rob$tau2, digits = 2)), "; ",
                  "Chi"^2, " = ", .(fmtx(ma_mace_rob$QE, digits = 2)),
                  ", df = ", .(ma_mace_rob$k - ma_mace_rob$p),
                  " (", italic(p), .(p_rob_pooled_het), "); ",
                  I^2, " = ", .(round(ma_mace_rob$I2)), "%")))

# Overall effect
# Low risk of bias
text(-10, 16, pos = 4, cex = 0.80,
     bquote(paste("Test for overall effect: ",
                  "Z = ", .(fmtx(ma_mace_low_rob$zval, digits = 2)),
                  " (", italic(p), .(p_rob_low_oe), ")")))

# High risk of bias
text(-10, 1, pos = 4, cex = 0.80,
     bquote(paste("Test for overall effect: ",
                  "Z = ", .(fmtx(ma_mace_high_rob$zval, digits = 2)),
                  " (", italic(p), .(p_rob_high_oe), ")")))

# Pooled
text(-10, -3, pos = 4, cex = 0.80,
     bquote(paste("Test for overall effect: ",
                  "Z = ", .(fmtx(ma_mace_rob$zval, digits = 2)),
                  " (", italic(p), .(p_rob_pooled_oe), ")")))

# Determine subgroup differences
rma(
  measure = "RR",   # Risk Ratio
  ai = mace_events_exp,  # Events in experimental group
  n1i = mace_n_exp,      # Total in experimental group
  ci = mace_events_cont, # Events in control group
  n2i = mace_n_cont,     # Total in control group
  slab = study,          # Study labels
  data = mace_data_rob,      # Data frame
  method = "REML",        # Method for random-effects model
  mod = rob_num
)

# Subgroup differences
text(-10, -4, pos = 4, cex = 0.80,
     bquote(paste("Test for subgroup differences: ",
                  "Chi"^2, " = ", .(fmtx(2.23, digits = 2)),
                  ", df = ", 1,
                  " (", italic(p), .(p_subgroup_diff_rob), ")")))

# Add label for axes
text(log(c(0.1, 10)), -5, c("Favours combination of SGLT-2 inhibitor and GLP-1 RA",
                            "Favours SGLT-2 inhibitor or GLP-1 RA monotherapy"),
     pos = c(4,2), offset = -7, cex = 0.80)

# Close PNG device
dev.off()

########################## Subgroup by MACE definition ######################### 

# Make risk of MACE definition categorical and numeric
mace_data_mace_def <- mace_data %>%
  mutate(tp_mace_cat = ifelse(ascvd_mace == 1, "Three point MACE",
                          "Expanded MACE"),
         tp_mace_num = ifelse(tp_mace_cat == "Three point MACE",
                               1, 0))

# Filter studies with three point MACE
mace_data_tp_mace <- mace_data_mace_def %>%
  filter(tp_mace_cat == "Three point MACE") %>%
  select(study,tp_mace_cat, tp_mace_num, mace_events_exp, mace_n_exp,
         mace_events_cont, mace_n_cont)

# Run meta-analysis for studies with a three point MACE endpoint
ma_mace_tp_mace <- rma(
  measure = "RR",   # Risk Ratio
  ai = mace_events_exp,  # Events in experimental group
  n1i = mace_n_exp,      # Total in experimental group
  ci = mace_events_cont, # Events in control group
  n2i = mace_n_cont,     # Total in control group
  slab = study,          # Study labels
  data = mace_data_tp_mace,      # Data frame
  method = "REML"        # Method for random-effects model
)

# Extract weights
mace_tp_mace_weights <- as.data.frame(paste0(fmtx(weights(ma_mace_tp_mace),
                                                     digits = 1), "%")) %>%
  rename(weight = `paste0(fmtx(weights(ma_mace_tp_mace), digits = 1), "%")`) %>%
  mutate(weight_num = as.numeric(gsub("%", "", weight)),
         weight_scaled = 0.80 + weight_num * 0.06) #Add numeric weights

#Extract rounded estimate and CI bound
pred_mace_tp_mace <- predict(ma_mace_tp_mace, transf = exp, digits = 2)
pred_mace_tp_mace <- fmtx(c(pred_mace_tp_mace$pred,
                            pred_mace_tp_mace$ci.lb,
                            pred_mace_tp_mace$ci.ub), digits=2)

# Add weights to dataframe
mace_data_tp_mace <- cbind(mace_data_tp_mace,
                              mace_tp_mace_weights)

# Filter studies with expanded MACE
mace_data_exp_mace <- mace_data_mace_def %>%
  filter(tp_mace_cat == "Expanded MACE") %>%
  select(study,tp_mace_cat, tp_mace_num, mace_events_exp, mace_n_exp,
         mace_events_cont, mace_n_cont)

# Run meta-analysis for studies with some concerns/serious/critical RoB
ma_mace_exp_mace <- rma(
  measure = "RR",   # Risk Ratio
  ai = mace_events_exp,  # Events in experimental group
  n1i = mace_n_exp,      # Total in experimental group
  ci = mace_events_cont, # Events in control group
  n2i = mace_n_cont,     # Total in control group
  slab = study,          # Study labels
  data = mace_data_exp_mace,      # Data frame
  method = "REML"        # Method for random-effects model
)

# Extract weights
mace_exp_mace_weights <- as.data.frame(paste0(fmtx(weights(ma_mace_exp_mace),
                                                     digits = 1), "%")) %>%
  rename(weight = `paste0(fmtx(weights(ma_mace_exp_mace), digits = 1), "%")`) %>%
  mutate(weight_num = as.numeric(gsub("%", "", weight)),
         weight_scaled = 0.7 + weight_num * 0.02) #Add numeric weights

#Extract rounded estimate and CI bound
pred_mace_exp_mace <- predict(ma_mace_exp_mace, transf = exp, digits = 2)
pred_mace_exp_mace <- fmtx(c(pred_mace_exp_mace$pred,
                             pred_mace_exp_mace$ci.lb,
                             pred_mace_exp_mace$ci.ub), digits=2)

# Add weights to dataframe
mace_data_exp_mace <- cbind(mace_data_exp_mace,
                            mace_exp_mace_weights)

# Bind dataframes with weights back together
mace_data_mace_def <- rbind(mace_data_tp_mace, mace_data_exp_mace)

# Order dataframe by subgroup and weights
# Order dataframe
mace_data_mace_def <- mace_data_mace_def %>%
  arrange(tp_mace_cat, desc(weight_num))

# Run meta-analysis for stratified by MACE definition
ma_mace_mace_def <- rma(
  measure = "RR",   # Risk Ratio
  ai = mace_events_exp,  # Events in experimental group
  n1i = mace_n_exp,      # Total in experimental group
  ci = mace_events_cont, # Events in control group
  n2i = mace_n_cont,     # Total in control group
  slab = study,          # Study labels
  data = mace_data_mace_def,      # Data frame
  method = "REML"        # Method for random-effects model
)

#Extract rounded estimate and CI bound
pred_mace_def <- predict(ma_mace_mace_def, transf = exp, digits = 2)
pred_mace_def <- fmtx(c(pred_mace_def$pred,
                        pred_mace_def$ci.lb,
                        pred_mace_def$ci.ub), digits=2)

# Extract weights
mace_mace_def_weights <- as.data.frame(paste0(fmtx(weights(ma_mace_mace_def),
                                                   digits = 1), "%")) %>%
  rename(weight_tp_mace = `paste0(fmtx(weights(ma_mace_mace_def), digits = 1), "%")`) %>%
  mutate(weight_num_tp_mace = as.numeric(gsub("%", "", weight_tp_mace)),
         weight_scaled_tp_mace = 0.70 + weight_num_tp_mace * 0.02) #Add numeric weights

# Add weights to dataframe
mace_data_mace_def <- cbind(mace_data_mace_def,
                            mace_mace_def_weights)

# Run meta-analysis for stratified for MACE definition
ma_mace_mace_def <- rma(
  measure = "RR",   # Risk Ratio
  ai = mace_events_exp,  # Events in experimental group
  n1i = mace_n_exp,      # Total in experimental group
  ci = mace_events_cont, # Events in control group
  n2i = mace_n_cont,     # Total in control group
  slab = study,          # Study labels
  data = mace_data_mace_def,      # Data frame
  method = "REML"        # Method for random-effects model
)

# Set up PNG for forest plot for MACE by MACE definition
png("supp_fig_7.png", width = 16000, height = 8000, res = 1200)

fp_mace_mace_def <- forest(ma_mace_mace_def,
                           xlim=c(-10, 4),
                           at=log(c(0.1, 0.5, 1, 2, 10)),
                           atransf=exp,
                           order = tp_mace_num,
                           xlab = "",
                           lty = c(1, 1, 0),
                           ilab = cbind(mace_events_exp, mace_n_exp, 
                                        mace_events_cont, mace_n_cont,
                                        weight_tp_mace),
                           ilab.xpos=c(-7, -6, -5, -4, -3),
                           cex=0.80,
                           ylim=c(-1, 24),
                           rows = c(5:8, 15:20),
                           mlab = "",
                           psize = weight_scaled_tp_mace,
                           header = c("Study", "Risk ratio [95% CI]"),
                           showweights = FALSE,
                           addfit = TRUE)

# Add pooled estimates of studies with three point MACE and other MACE
addpoly(ma_mace_tp_mace, row = 13, cex = 0.80)
addpoly(ma_mace_exp_mace, row = 3, cex = 0.80)

# hide non-bold summary estimates and study labels
rect(-10, c(14, 4), -7.25, c(12, 2), col = "White", border = NA)

# Hide point estimates RE
rect(2.5, c(14, 4),
     4, c(12, -4), col = "White", border = NA)

# Place summary estimates back in bold
text(fp_mace_mace_def$textpos[2], -1,
     paste0(pred_mace_def[1], " [", pred_mace_def[2], ",  ",
            pred_mace_def[3], "]"),
     pos=2, font = 2, cex = 0.80)

text(fp_mace_mace_def$textpos[2], 13,
     paste0(pred_mace_tp_mace[1], " [", pred_mace_tp_mace[2], ",  ",
            pred_mace_tp_mace[3], "]"),
     pos=2, font = 2, cex = 0.80)

text(fp_mace_mace_def$textpos[2], 3,
     paste0(pred_mace_exp_mace[1], " [", pred_mace_exp_mace[2], ",  ",
            pred_mace_exp_mace[3], "]"),
     pos=2, font = 2, cex = 0.80)

# Add horizontal line at the top
segments(-10, 22, 4, 22, lwd = 0.8)

# Expand margins
par(xpd = NA)

# Add labels on top
text(c(-7, -6, -5, -4, -3), 23,
     c("Events", "Total", "Events", "Total", "Weight"), cex = 0.80,
     font = 2)
text(c(-6.5, -4.5, 0), 24,
     c("Combination therapy", "Monotherapy", "Risk ratio"),
     cex = 0.80, font = 2)
text(0, 23, c("MH Random, 95% CI"), cex = 0.80, font = 2)

# Add outcome labels
text(c(-10), c(21, 9),
     c("Three point MACE",
       "Other MACE"),
     pos = 4, font = 2, cex = 0.80)

# Add Total labels:
text(-10, -1, pos = 4, "Total (95% CI)", font = 2, cex = 0.80)

# Add subtotal labels
text(-10, c(3, 13), "Subtotal (95% CI)", font = 2, cex = 0.80, pos = 4)

#Add text for total events
text(c(-6, -4), -1, c(sum(mace_data_mace_def$mace_n_exp),
                      sum(mace_data_mace_def$mace_n_cont)),
     font = 2, cex = 0.80)

text(c(-7, -5), -1, c(sum(mace_data_mace_def$mace_events_exp),
                      sum(mace_data_mace_def$mace_events_cont)),
     cex = 0.80)

# Add text for subtotal events
text(c(-6, -4), 13, c(sum(mace_data_tp_mace$mace_n_exp),
                      sum(mace_data_tp_mace$mace_n_cont)), font = 2,
     cex = 0.80)

text(c(-7, -5), 13, c(sum(mace_data_tp_mace$mace_events_exp),
                      sum(mace_data_tp_mace$mace_events_cont)),
     cex = 0.80)

text(c(-6, -4), 3, c(sum(mace_data_exp_mace$mace_n_exp),
                     sum(mace_data_exp_mace$mace_n_cont)), font = 2,
     cex = 0.80)

text(c(-7, -5), 3, c(sum(mace_data_exp_mace$mace_events_exp),
                     sum(mace_data_exp_mace$mace_events_cont)),
     cex = 0.80)

# Calculate sum of weights for studies with a three-point and expanded MACE
mace_data_mace_def %>%
  group_by(tp_mace_cat) %>%
  summarise(sum_weight = sum(weight_num_tp_mace))

# Add sum of weights
text(-3, c(13, 3, -1), c("39.3%", "60.6%", "100%"), cex = 0.80, font = 2)

# Extract p-values
p_tp_mace_het    <- fmtp(ma_mace_tp_mace$QEp, digits = 2, pname = "",
                         add0 = TRUE, sep = TRUE, equal = TRUE)
p_exp_mace_het   <- fmtp(ma_mace_exp_mace$QEp, digits = 2, pname = "",
                         add0 = TRUE, sep = TRUE, equal = TRUE)
p_mace_def_het   <- fmtp(ma_mace_mace_def$QEp, digits = 2, pname = "",
                         add0 = TRUE, sep = TRUE, equal = TRUE)

p_tp_mace_oe     <- fmtp(ma_mace_tp_mace$pval, digits = 2, pname = "",
                         add0 = TRUE, sep = TRUE, equal = TRUE)
p_exp_mace_oe    <- fmtp(ma_mace_exp_mace$pval, digits = 2, pname = "",
                         add0 = TRUE, sep = TRUE, equal = TRUE)
p_mace_def_oe    <- fmtp(ma_mace_mace_def$pval, digits = 2, pname = "",
                         add0 = TRUE, sep = TRUE, equal = TRUE)

# Subgroup difference p-value
p_subgroup_diff_mace_def <- fmtp(0.09, digits = 2, pname = "", add0 = TRUE,
                                 sep = TRUE, equal = TRUE)

# Add heterogeneity statistics
# Three point MACE
text(-10, 12, pos = 4, cex = 0.80,
     bquote(paste("Heterogeneity: ",
                  "Tau"^2, " = ", .(fmtx(ma_mace_tp_mace$tau2, digits = 2)), "; ",
                  "Chi"^2, " = ", .(fmtx(ma_mace_tp_mace$QE, digits = 2)),
                  ", df = ", .(ma_mace_tp_mace$k - ma_mace_tp_mace$p),
                  " (", italic(p), .(p_tp_mace_het), "); ",
                  I^2, " = ", .(round(ma_mace_tp_mace$I2)), "%")))

# Other MACE
text(-10, 2, pos = 4, cex = 0.80,
     bquote(paste("Heterogeneity: ",
                  "Tau"^2, " = ", .(fmtx(ma_mace_exp_mace$tau2, digits = 2)), "; ",
                  "Chi"^2, " = ", .(fmtx(ma_mace_exp_mace$QE, digits = 2)),
                  ", df = ", .(ma_mace_exp_mace$k - ma_mace_exp_mace$p),
                  " (", italic(p), .(p_exp_mace_het), "); ",
                  I^2, " = ", .(round(ma_mace_exp_mace$I2)), "%")))

# Pooled
text(-10, -2, pos = 4, cex = 0.80,
     bquote(paste("Heterogeneity: ",
                  "Tau"^2, " = ", .(fmtx(ma_mace_mace_def$tau2, digits = 2)), "; ",
                  "Chi"^2, " = ", .(fmtx(ma_mace_mace_def$QE, digits = 2)),
                  ", df = ", .(ma_mace_mace_def$k - ma_mace_mace_def$p),
                  " (", italic(p), .(p_mace_def_het), "); ",
                  I^2, " = ", .(round(ma_mace_mace_def$I2)), "%")))

# Add overall effect
# Three point MACE
text(-10, 11, pos = 4, cex = 0.80,
     bquote(paste("Test for overall effect: ",
                  "Z = ", .(fmtx(ma_mace_tp_mace$zval, digits = 2)),
                  " (", italic(p), .(p_tp_mace_oe), ")")))

# Other MACE
text(-10, 1, pos = 4, cex = 0.80,
     bquote(paste("Test for overall effect: ",
                  "Z = ", .(fmtx(ma_mace_exp_mace$zval, digits = 2)),
                  " (", italic(p), .(p_exp_mace_oe), ")")))

# Pooled
text(-10, -3, pos = 4, cex = 0.80,
     bquote(paste("Test for overall effect: ",
                  "Z = ", .(fmtx(ma_mace_mace_def$zval, digits = 2)),
                  " (", italic(p), .(p_mace_def_oe), ")")))

# Determine subgroup differences
rma(
  measure = "RR",   # Risk Ratio
  ai = mace_events_exp,  # Events in experimental group
  n1i = mace_n_exp,      # Total in experimental group
  ci = mace_events_cont, # Events in control group
  n2i = mace_n_cont,     # Total in control group
  slab = study,          # Study labels
  data = mace_data_mace_def,      # Data frame
  method = "REML",        # Method for random-effects model
  mod = tp_mace_num
)

# Add subgroup differences
text(-10, -4, pos = 4, cex = 0.80,
     bquote(paste("Test for subgroup differences: ",
                  "Chi"^2, " = ", .(fmtx(2.81, digits = 2)),
                  ", df = ", 1,
                  " (", italic(p), .(p_subgroup_diff_mace_def), ")")))

# Add label for axes
text(log(c(0.1, 10)), -5, c("Favours combination of SGLT-2 inhibitor and GLP-1 RA",
                            "Favours SGLT-2 inhibitor or GLP-1 RA monotherapy"),
     pos = c(4,2), offset = -7, cex = 0.80)

# Close PNG device
dev.off()

############################ Confounding adjustment ############################

# Filter studies for confounding analysis
mace_data_confounding <- mace_data %>%
  filter(!is.na(confounding))

# Filter studies with propensity score/IPTW
mace_data_confounding_ps <- mace_data_confounding %>%
  filter(confounding == 1) %>%
  select(study,confounding, mace_events_exp, mace_n_exp,
         mace_events_cont, mace_n_cont)

# Run meta-analysis for studies with PS/IPTW
ma_mace_confounding_ps <- rma(
  measure = "RR",   # Risk Ratio
  ai = mace_events_exp,  # Events in experimental group
  n1i = mace_n_exp,      # Total in experimental group
  ci = mace_events_cont, # Events in control group
  n2i = mace_n_cont,     # Total in control group
  slab = study,          # Study labels
  data = mace_data_confounding_ps,      # Data frame
  method = "REML"        # Method for random-effects model
)

# Extract weights
mace_confounding_ps_weights <- as.data.frame(paste0(fmtx(weights(ma_mace_confounding_ps),
                                                  digits = 1), "%")) %>%
  rename(weight = `paste0(fmtx(weights(ma_mace_confounding_ps), digits = 1), "%")`) %>%
  mutate(weight_num = as.numeric(gsub("%", "", weight)),
         weight_scaled = 0.7 + weight_num * 0.02) #Add numeric weights

#Extract rounded estimate and CI bound
pred_mace_confounding_ps <- predict(ma_mace_confounding_ps, transf = exp, digits = 2)
pred_mace_confounding_ps <- fmtx(c(pred_mace_confounding_ps$pred,
                                   pred_mace_confounding_ps$ci.lb,
                                   pred_mace_confounding_ps$ci.ub), digits=2)

# Add weights to dataframe
mace_data_confounding_ps <- cbind(mace_data_confounding_ps,
                                  mace_confounding_ps_weights)

# Filter studies with other methods for adjustment
mace_data_confounding_mv <- mace_data_confounding %>%
  filter(confounding == 0) %>%
  select(study,confounding, mace_events_exp, mace_n_exp,
         mace_events_cont, mace_n_cont)

# Run meta-analysis for studies with multivariable adjustment
ma_mace_confounding_mv <- rma(
  measure = "RR",   # Risk Ratio
  ai = mace_events_exp,  # Events in experimental group
  n1i = mace_n_exp,      # Total in experimental group
  ci = mace_events_cont, # Events in control group
  n2i = mace_n_cont,     # Total in control group
  slab = study,          # Study labels
  data = mace_data_confounding_mv,      # Data frame
  method = "REML"        # Method for random-effects model
)

# Extract weights
mace_confounding_mv_weights <- as.data.frame(paste0(fmtx(weights(ma_mace_confounding_mv),
                                                         digits = 1), "%")) %>%
  rename(weight = `paste0(fmtx(weights(ma_mace_confounding_mv), digits = 1), "%")`) %>%
  mutate(weight_num = as.numeric(gsub("%", "", weight)),
         weight_scaled = 0.7 + weight_num * 0.02) #Add numeric weights

#Extract rounded estimate and CI bound
pred_mace_confounding_mv <- predict(ma_mace_confounding_mv, transf = exp, digits = 2)
pred_mace_confounding_mv <- fmtx(c(pred_mace_confounding_mv$pred,
                                   pred_mace_confounding_mv$ci.lb,
                                   pred_mace_confounding_mv$ci.ub), digits=2)

# Add weights to dataframe
mace_data_confounding_mv <- cbind(mace_data_confounding_mv,
                                  mace_confounding_mv_weights)

# Bind dataframes with weights back together
mace_data_confounding <- rbind(mace_data_confounding_ps,
                               mace_data_confounding_mv)

# Order dataframe by subgroup and weights
# Order dataframe
mace_data_confounding <- mace_data_confounding %>%
  arrange(confounding, desc(weight_num))

# Run meta-analysis for stratified by method to adjust for confounding
ma_mace_confounding <- rma(
  measure = "RR",   # Risk Ratio
  ai = mace_events_exp,  # Events in experimental group
  n1i = mace_n_exp,      # Total in experimental group
  ci = mace_events_cont, # Events in control group
  n2i = mace_n_cont,     # Total in control group
  slab = study,          # Study labels
  data = mace_data_confounding,      # Data frame
  method = "REML"        # Method for random-effects model
)

#Extract rounded estimate and CI bound
pred_mace_confounding <- predict(ma_mace_confounding, transf = exp, digits = 2)
pred_mace_confounding <- fmtx(c(pred_mace_confounding$pred,
                        pred_mace_confounding$ci.lb,
                        pred_mace_confounding$ci.ub), digits=2)

# Extract weights
mace_confounding_weights <- as.data.frame(paste0(fmtx(weights(ma_mace_confounding),
                                              digits = 1), "%")) %>%
  rename(weight_confounding = `paste0(fmtx(weights(ma_mace_confounding), digits = 1), "%")`) %>%
  mutate(weight_num_confounding = as.numeric(gsub("%", "", weight_confounding)),
         weight_scaled_confounding = 0.70 + weight_num_confounding * 0.02) #Add numeric weights

# Add weights to dataframe
mace_data_confounding <- cbind(mace_data_confounding,
                       mace_confounding_weights)

# Run meta-analysis for stratified for method to adjust for confounding
ma_mace_confounding <- rma(
  measure = "RR",   # Risk Ratio
  ai = mace_events_exp,  # Events in experimental group
  n1i = mace_n_exp,      # Total in experimental group
  ci = mace_events_cont, # Events in control group
  n2i = mace_n_cont,     # Total in control group
  slab = study,          # Study labels
  data = mace_data_confounding,      # Data frame
  method = "REML"        # Method for random-effects model
)

# Set up PNG for forest plot for MACE by method to adjust for confounding
png("supp_fig_8.png", width = 16000, height = 8000, res = 1200)

fp_mace_confounding <- forest(ma_mace_confounding,
                      xlim=c(-10, 4),
                      at=log(c(0.1, 0.5, 1, 2, 10)),
                      atransf=exp,
                      order = confounding,
                      xlab = "",
                      lty = c(1, 1, 0),
                      ilab = cbind(mace_events_exp, mace_n_exp, 
                                   mace_events_cont, mace_n_cont,
                                   weight_confounding),
                      ilab.xpos=c(-7, -6, -5, -4, -3),
                      cex=0.80,
                      ylim=c(-1, 24),
                      rows = c(5:6, 13:20),
                      mlab = "",
                      psize = weight_scaled_confounding,
                      header = c("Study", "Risk ratio [95% CI]"),
                      showweights = FALSE,
                      addfit = TRUE)

# Add pooled estimates of studies PS/IPTW adjustment and other adjustment
addpoly(ma_mace_confounding_ps, row = 11, cex = 0.80)
addpoly(ma_mace_confounding_mv, row = 3, cex = 0.80)

# hide non-bold summary estimates and study labels
rect(-10, c(12, 4), -7.25, c(10, 2), col = "White", border = NA)

# Hide point estimates RE
rect(2.5, c(12, 4),
     4, c(10, -4), col = "White", border = NA)

# Place summary estimates back in bold
text(fp_mace_confounding$textpos[2], -1,
     paste0(pred_mace_confounding[1], " [", pred_mace_confounding[2], ",  ",
            pred_mace_confounding[3], "]"),
     pos=2, font = 2, cex = 0.80)

text(fp_mace_confounding$textpos[2], 11,
     paste0(pred_mace_confounding_ps[1], " [", pred_mace_confounding_ps[2], ",  ",
            pred_mace_confounding_ps[3], "]"),
     pos=2, font = 2, cex = 0.80)

text(fp_mace_confounding$textpos[2], 3,
     paste0(pred_mace_confounding_mv[1], " [", pred_mace_confounding_mv[2], ",  ",
            pred_mace_confounding_mv[3], "]"),
     pos=2, font = 2, cex = 0.80)

# Add horizontal line at the top
segments(-10, 22, 4, 22, lwd = 0.8)

# Expand margins
par(xpd = NA)

# Add labels on top
text(c(-7, -6, -5, -4, -3), 23,
     c("Events", "Total", "Events", "Total", "Weight"), cex = 0.80,
     font = 2)
text(c(-6.5, -4.5, 0), 24,
     c("Combination therapy", "Monotherapy", "Risk ratio"),
     cex = 0.80, font = 2)
text(0, 23, c("MH Random, 95% CI"), cex = 0.80, font = 2)

# Add outcome labels
text(c(-10), c(21, 7),
     c("Propensity scores/IPTW",
       "Other method to adjust for confounding"),
     pos = 4, font = 2, cex = 0.80)

# Add Total labels:
text(-10, -1, pos = 4, "Total (95% CI)", font = 2, cex = 0.80)

# Add subtotal labels
text(-10, c(3, 11), "Subtotal (95% CI)", font = 2, cex = 0.80, pos = 4)

#Add text for total events
text(c(-6, -4), -1, c(sum(mace_data_confounding$mace_n_exp),
                      sum(mace_data_confounding$mace_n_cont)),
     font = 2, cex = 0.80)

text(c(-7, -5), -1, c(sum(mace_data_confounding$mace_events_exp),
                      sum(mace_data_confounding$mace_events_cont)),
     cex = 0.80)

# Add text for subtotal events
text(c(-6, -4), 11, c(sum(mace_data_confounding_ps$mace_n_exp),
                      sum(mace_data_confounding_ps$mace_n_cont)), font = 2,
     cex = 0.80)

text(c(-7, -5), 11, c(sum(mace_data_confounding_ps$mace_events_exp),
                      sum(mace_data_confounding_ps$mace_events_cont)),
     cex = 0.80)

text(c(-6, -4), 3, c(sum(mace_data_confounding_mv$mace_n_exp),
                     sum(mace_data_confounding_mv$mace_n_cont)), font = 2,
     cex = 0.80)

text(c(-7, -5), 3, c(sum(mace_data_confounding_mv$mace_events_exp),
                     sum(mace_data_confounding_mv$mace_events_cont)),
     cex = 0.80)

# Calculate sum of weights for studies with a low and high risk of bias
mace_data_confounding %>%
  group_by(confounding) %>%
  summarise(sum_weight = sum(weight_num_confounding))

# Add sum of weights
text(-3, c(11, 3, -1), c("83.5%", "16.4%", "100%"), cex = 0.80, font = 2)

# Extract p-values
p_confounding_ps_het    <- fmtp(ma_mace_confounding_ps$QEp, digits = 2,
                                pname = "", add0 = TRUE, sep = TRUE,
                                equal = TRUE)
p_confounding_mv_het    <- fmtp(ma_mace_confounding_mv$QEp, digits = 2,
                                pname = "", add0 = TRUE, sep = TRUE,
                                equal = TRUE)
p_confounding_pooled_het <- fmtp(ma_mace_confounding$QEp, digits = 2,
                                 pname = "", add0 = TRUE, sep = TRUE,
                                 equal = TRUE)

p_confounding_ps_oe     <- fmtp(ma_mace_confounding_ps$pval, digits = 2,
                                pname = "", add0 = TRUE, sep = TRUE,
                                equal = TRUE)
p_confounding_mv_oe     <- fmtp(ma_mace_confounding_mv$pval, digits = 2,
                                pname = "", add0 = TRUE, sep = TRUE,
                                equal = TRUE)
p_confounding_pooled_oe <- fmtp(ma_mace_confounding$pval, digits = 2,
                                pname = "", add0 = TRUE, sep = TRUE,
                                equal = TRUE)

# Subgroup difference p-value
p_subgroup_diff_confounding <- fmtp(0.07, digits = 2, pname = "",
                                    add0 = TRUE, sep = TRUE, equal = TRUE)

#Add heterogeneity statistics
# Propensity scores/IPTW
text(-10, 10, pos = 4, cex = 0.80,
     bquote(paste("Heterogeneity: ",
                  "Tau"^2, " = ", .(fmtx(ma_mace_confounding_ps$tau2, digits = 2)), "; ",
                  "Chi"^2, " = ", .(fmtx(ma_mace_confounding_ps$QE, digits = 2)),
                  ", df = ", .(ma_mace_confounding_ps$k - ma_mace_confounding_ps$p),
                  " (", italic(p), .(p_confounding_ps_het), "); ",
                  I^2, " = ", .(round(ma_mace_confounding_ps$I2)), "%")))

# Other method to adjust for confounding
text(-10, 2, pos = 4, cex = 0.80,
     bquote(paste("Heterogeneity: ",
                  "Tau"^2, " = ", .(fmtx(ma_mace_confounding_mv$tau2, digits = 2)), "; ",
                  "Chi"^2, " = ", .(fmtx(ma_mace_confounding_mv$QE, digits = 2)),
                  ", df = ", .(ma_mace_confounding_mv$k - ma_mace_confounding_mv$p),
                  " (", italic(p), .(p_confounding_mv_het), "); ",
                  I^2, " = ", .(round(ma_mace_confounding_mv$I2)), "%")))

# Pooled
text(-10, -2, pos = 4, cex = 0.80,
     bquote(paste("Heterogeneity: ",
                  "Tau"^2, " = ", .(fmtx(ma_mace_confounding$tau2, digits = 2)), "; ",
                  "Chi"^2, " = ", .(fmtx(ma_mace_confounding$QE, digits = 2)),
                  ", df = ", .(ma_mace_confounding$k - ma_mace_confounding$p),
                  " (", italic(p), .(p_confounding_pooled_het), "); ",
                  I^2, " = ", .(round(ma_mace_confounding$I2)), "%")))

# Add overall effect
# Propensity scores/IPTW
text(-10, 9, pos = 4, cex = 0.80,
     bquote(paste("Test for overall effect: ",
                  "Z = ", .(fmtx(ma_mace_confounding_ps$zval, digits = 2)),
                  " (", italic(p), .(p_confounding_ps_oe), ")")))

# Other method to adjust for confounding
text(-10, 1, pos = 4, cex = 0.80,
     bquote(paste("Test for overall effect: ",
                  "Z = ", .(fmtx(ma_mace_confounding_mv$zval, digits = 2)),
                  " (", italic(p), .(p_confounding_mv_oe), ")")))

# Pooled
text(-10, -3, pos = 4, cex = 0.80,
     bquote(paste("Test for overall effect: ",
                  "Z = ", .(fmtx(ma_mace_confounding$zval, digits = 2)),
                  " (", italic(p), .(p_confounding_pooled_oe), ")")))

# Determine subgroup differences
rma(
  measure = "RR",   # Risk Ratio
  ai = mace_events_exp,  # Events in experimental group
  n1i = mace_n_exp,      # Total in experimental group
  ci = mace_events_cont, # Events in control group
  n2i = mace_n_cont,     # Total in control group
  slab = study,          # Study labels
  data = mace_data_confounding,      # Data frame
  method = "REML",        # Method for random-effects model
  mod = confounding
)

# Add subgroup differences
text(-10, -4, pos = 4, cex = 0.80,
     bquote(paste("Test for subgroup differences: ",
                  "Chi"^2, " = ", .(fmtx(3.28, digits = 2)),
                  ", df = ", 1,
                  " (", italic(p), .(p_subgroup_diff_confounding), ")")))

# Add label for axes
text(log(c(0.1, 10)), -5, c("Favours combination of SGLT-2 inhibitor and GLP-1 RA",
                            "Favours SGLT-2 inhibitor or GLP-1 RA monotherapy"),
     pos = c(4,2), offset = -7, cex = 0.80)

# Close PNG device
dev.off()

################################## Data source ################################# 

mace_data_source <- mace_data %>%
  filter(!is.na(data_source))

mace_data_ehr <- mace_data_source %>%
  filter(data_source == 1) %>%
  select(study,data_source, mace_events_exp, mace_n_exp,
         mace_events_cont, mace_n_cont)

# Run meta-analysis for studies with EHR data
ma_mace_ehr <- rma(
  measure = "RR",   # Risk Ratio
  ai = mace_events_exp,  # Events in experimental group
  n1i = mace_n_exp,      # Total in experimental group
  ci = mace_events_cont, # Events in control group
  n2i = mace_n_cont,     # Total in control group
  slab = study,          # Study labels
  data = mace_data_ehr,      # Data frame
  method = "REML"        # Method for random-effects model
)

# Extract weights
mace_ehr_weights <- as.data.frame(paste0(fmtx(weights(ma_mace_ehr),
                                                         digits = 1), "%")) %>%
  rename(weight = `paste0(fmtx(weights(ma_mace_ehr), digits = 1), "%")`) %>%
  mutate(weight_num = as.numeric(gsub("%", "", weight)),
         weight_scaled = 0.7 + weight_num * 0.02) #Add numeric weights

#Extract rounded estimate and CI bound
pred_mace_ehr <- predict(ma_mace_ehr, transf = exp, digits = 2)
pred_mace_ehr <- fmtx(c(pred_mace_ehr$pred,
                        pred_mace_ehr$ci.lb,
                        pred_mace_ehr$ci.ub), digits=2)

# Add weights to dataframe
mace_data_ehr <- cbind(mace_data_ehr, mace_ehr_weights)

# Filter studies with other methods for adjustment
mace_data_other <- mace_data_source %>%
  filter(data_source == 0) %>%
  select(study,data_source, mace_events_exp, mace_n_exp,
         mace_events_cont, mace_n_cont)

# Run meta-analysis for studies with other data sources
ma_mace_other <- rma(
  measure = "RR",   # Risk Ratio
  ai = mace_events_exp,  # Events in experimental group
  n1i = mace_n_exp,      # Total in experimental group
  ci = mace_events_cont, # Events in control group
  n2i = mace_n_cont,     # Total in control group
  slab = study,          # Study labels
  data = mace_data_other,      # Data frame
  method = "REML"        # Method for random-effects model
)

# Extract weights
mace_other_weights <- as.data.frame(paste0(fmtx(weights(ma_mace_other),
                                                         digits = 1), "%")) %>%
  rename(weight = `paste0(fmtx(weights(ma_mace_other), digits = 1), "%")`) %>%
  mutate(weight_num = as.numeric(gsub("%", "", weight)),
         weight_scaled = 0.7 + weight_num * 0.02) #Add numeric weights

#Extract rounded estimate and CI bound
pred_mace_other <- predict(ma_mace_other, transf = exp, digits = 2)
pred_mace_other <- fmtx(c(pred_mace_other$pred,
                          pred_mace_other$ci.lb,
                          pred_mace_other$ci.ub), digits=2)

# Add weights to dataframe
mace_data_other <- cbind(mace_data_other, mace_other_weights)

# Bind dataframes with weights back together
mace_data_source <- rbind(mace_data_ehr,
                               mace_data_other)

# Order dataframe by subgroup and weights
# Order dataframe
mace_data_source <- mace_data_source %>%
  arrange(data_source, desc(weight_num))

# Run meta-analysis for stratified by data source
ma_mace_data_source <- rma(
  measure = "RR",   # Risk Ratio
  ai = mace_events_exp,  # Events in experimental group
  n1i = mace_n_exp,      # Total in experimental group
  ci = mace_events_cont, # Events in control group
  n2i = mace_n_cont,     # Total in control group
  slab = study,          # Study labels
  data = mace_data_source,      # Data frame
  method = "REML"        # Method for random-effects model
)

#Extract rounded estimate and CI bound
pred_mace_data_source <- predict(ma_mace_data_source, transf = exp, digits = 2)
pred_mace_data_source <- fmtx(c(pred_mace_data_source$pred,
                                pred_mace_data_source$ci.lb,
                                pred_mace_data_source$ci.ub), digits=2)

# Extract weights
mace_source_weights <- as.data.frame(paste0(fmtx(weights(ma_mace_data_source),
                                                      digits = 1), "%")) %>%
  rename(weight_source = `paste0(fmtx(weights(ma_mace_data_source), digits = 1), "%")`) %>%
  mutate(weight_num_source = as.numeric(gsub("%", "", weight_source)),
         weight_scaled_source = 0.70 + weight_num_source * 0.02) #Add numeric weights

# Add weights to dataframe
mace_data_source <- cbind(mace_data_source,
                               mace_source_weights)

# Run meta-analysis for stratified data source
ma_mace_data_source <- rma(
  measure = "RR",   # Risk Ratio
  ai = mace_events_exp,  # Events in experimental group
  n1i = mace_n_exp,      # Total in experimental group
  ci = mace_events_cont, # Events in control group
  n2i = mace_n_cont,     # Total in control group
  slab = study,          # Study labels
  data = mace_data_source,      # Data frame
  method = "REML"        # Method for random-effects model
)

# Set up PNG for forest plot for MACE by data source
png("supp_fig_9.png", width = 16000, height = 8000, res = 1200)

fp_mace_data_source <- forest(ma_mace_data_source,
                              xlim=c(-10, 4),
                              at=log(c(0.1, 0.5, 1, 2, 10)),
                              atransf=exp,
                              order = data_source,
                              xlab = "",
                              lty = c(1, 1, 0),
                              ilab = cbind(mace_events_exp, mace_n_exp, 
                                           mace_events_cont, mace_n_cont,
                                           weight_source),
                              ilab.xpos=c(-7, -6, -5, -4, -3),
                              cex=0.80,
                              ylim=c(-1, 24),
                              rows = c(5:8, 15:20),
                              mlab = "",
                              psize = weight_scaled_source,
                              header = c("Study", "Risk ratio [95% CI]"),
                              showweights = FALSE,
                              addfit = TRUE)

# Add pooled estimates of studies EHR data and outher sources
addpoly(ma_mace_ehr, row = 13, cex = 0.80)
addpoly(ma_mace_other, row = 3, cex = 0.80)

# hide non-bold summary estimates and study labels
rect(-10, c(14, 4), -7.25, c(12, 2), col = "White", border = NA)

# Hide point estimates RE
rect(2.5, c(14, 4),
     4, c(12, -4), col = "White", border = NA)

# Place summary estimates back in bold
text(fp_mace_data_source$textpos[2], -1,
     paste0(pred_mace_data_source[1], " [", pred_mace_data_source[2], ",  ",
            pred_mace_data_source[3], "]"),
     pos=2, font = 2, cex = 0.80)

text(fp_mace_data_source$textpos[2], 13,
     paste0(pred_mace_ehr[1], " [", pred_mace_ehr[2], ",  ",
            pred_mace_ehr[3], "]"),
     pos=2, font = 2, cex = 0.80)

text(fp_mace_data_source$textpos[2], 3,
     paste0(pred_mace_other[1], " [", pred_mace_other[2], ",  ",
            pred_mace_other[3], "]"),
     pos=2, font = 2, cex = 0.80)

# Add horizontal line at the top
segments(-10, 22, 4, 22, lwd = 0.8)

# Expand margins
par(xpd = NA)

# Add labels on top
text(c(-7, -6, -5, -4, -3), 23,
     c("Events", "Total", "Events", "Total", "Weight"), cex = 0.80,
     font = 2)
text(c(-6.5, -4.5, 0), 24,
     c("Combination therapy", "Monotherapy", "Risk ratio"),
     cex = 0.80, font = 2)
text(0, 23, c("MH Random, 95% CI"), cex = 0.80, font = 2)

# Add outcome labels
text(c(-10), c(21, 9),
     c("Electronic healthcare records",
       "Other data sources"),
     pos = 4, font = 2, cex = 0.80)

# Add Total labels:
text(-10, -1, pos = 4, "Total (95% CI)", font = 2, cex = 0.80)

# Add subtotal labels
text(-10, c(3, 13), "Subtotal (95% CI)", font = 2, cex = 0.80, pos = 4)

#Add text for total events
text(c(-6, -4), -1, c(sum(mace_data_source$mace_n_exp),
                      sum(mace_data_source$mace_n_cont)),
     font = 2, cex = 0.80)

text(c(-7, -5), -1, c(sum(mace_data_source$mace_events_exp),
                      sum(mace_data_source$mace_events_cont)),
     cex = 0.80)

# Add text for subtotal events
text(c(-6, -4), 13, c(sum(mace_data_ehr$mace_n_exp),
                      sum(mace_data_ehr$mace_n_cont)), font = 2,
     cex = 0.80)

text(c(-7, -5), 13, c(sum(mace_data_ehr$mace_events_exp),
                      sum(mace_data_ehr$mace_events_cont)),
     cex = 0.80)

text(c(-6, -4), 3, c(sum(mace_data_other$mace_n_exp),
                     sum(mace_data_other$mace_n_cont)), font = 2,
     cex = 0.80)

text(c(-7, -5), 3, c(sum(mace_data_other$mace_events_exp),
                     sum(mace_data_other$mace_events_cont)),
     cex = 0.80)

# Calculate sum of weights for studies with a low and high risk of bias
mace_data_source %>%
  group_by(data_source) %>%
  summarise(sum_weight = sum(weight_num_source))

# Add sum of weights
text(-3, c(13, 3, -1), c("59.6%", "40.3%", "100%"), cex = 0.80, font = 2)

# Extract p-values
p_ehr_het        <- fmtp(ma_mace_ehr$QEp, digits = 2, pname = "",
                         add0 = TRUE, sep = TRUE, equal = TRUE)
p_other_het      <- fmtp(ma_mace_other$QEp, digits = 2, pname = "",
                         add0 = TRUE, sep = TRUE, equal = TRUE)
p_data_het       <- fmtp(ma_mace_data_source$QEp, digits = 2, pname = "",
                         add0 = TRUE, sep = TRUE, equal = TRUE)

p_ehr_oe         <- fmtp(ma_mace_ehr$pval, digits = 2, pname = "",
                         add0 = TRUE, sep = TRUE, equal = TRUE)
p_other_oe       <- fmtp(ma_mace_other$pval, digits = 2, pname = "",
                         add0 = TRUE, sep = TRUE, equal = TRUE)
p_data_oe        <- fmtp(ma_mace_data_source$pval, digits = 2, pname = "",
                         add0 = TRUE, sep = TRUE, equal = TRUE)

# Subgroup difference p-value
p_subgroup_diff_data <- fmtp(0.61, digits = 2, pname = "", add0 = TRUE,
                             sep = TRUE, equal = TRUE)

#Add heterogeneity statistics
# EHR data
text(-10, 12, pos = 4, cex = 0.80,
     bquote(paste("Heterogeneity: ",
                  "Tau"^2, " = ", .(fmtx(ma_mace_ehr$tau2, digits = 2)), "; ",
                  "Chi"^2, " = ", .(fmtx(ma_mace_ehr$QE, digits = 2)),
                  ", df = ", .(ma_mace_ehr$k - ma_mace_ehr$p),
                  " (", italic(p), .(p_ehr_het), "); ",
                  I^2, " = ", .(round(ma_mace_ehr$I2)), "%")))

# Other data sources
text(-10, 2, pos = 4, cex = 0.80,
     bquote(paste("Heterogeneity: ",
                  "Tau"^2, " = ", .(fmtx(ma_mace_other$tau2, digits = 2)), "; ",
                  "Chi"^2, " = ", .(fmtx(ma_mace_other$QE, digits = 2)),
                  ", df = ", .(ma_mace_other$k - ma_mace_other$p),
                  " (", italic(p), .(p_other_het), "); ",
                  I^2, " = ", .(round(ma_mace_other$I2)), "%")))

# Pooled
text(-10, -2, pos = 4, cex = 0.80,
     bquote(paste("Heterogeneity: ",
                  "Tau"^2, " = ", .(fmtx(ma_mace_data_source$tau2, digits = 2)), "; ",
                  "Chi"^2, " = ", .(fmtx(ma_mace_data_source$QE, digits = 2)),
                  ", df = ", .(ma_mace_data_source$k - ma_mace_data_source$p),
                  " (", italic(p), .(p_data_het), "); ",
                  I^2, " = ", .(round(ma_mace_data_source$I2)), "%")))

# Add overall effect
# EHR data
text(-10, 11, pos = 4, cex = 0.80,
     bquote(paste("Test for overall effect: ",
                  "Z = ", .(fmtx(ma_mace_ehr$zval, digits = 2)),
                  " (", italic(p), .(p_ehr_oe), ")")))

# Other data sources
text(-10, 1, pos = 4, cex = 0.80,
     bquote(paste("Test for overall effect: ",
                  "Z = ", .(fmtx(ma_mace_other$zval, digits = 2)),
                  " (", italic(p), .(p_other_oe), ")")))

# Pooled
text(-10, -3, pos = 4, cex = 0.80,
     bquote(paste("Test for overall effect: ",
                  "Z = ", .(fmtx(ma_mace_data_source$zval, digits = 2)),
                  " (", italic(p), .(p_data_oe), ")")))

# Determine subgroup differences
rma(
  measure = "RR",   # Risk Ratio
  ai = mace_events_exp,  # Events in experimental group
  n1i = mace_n_exp,      # Total in experimental group
  ci = mace_events_cont, # Events in control group
  n2i = mace_n_cont,     # Total in control group
  slab = study,          # Study labels
  data = mace_data_source,      # Data frame
  method = "REML",        # Method for random-effects model
  mod = data_source
)

# Add subgroup differences
text(-10, -4, pos = 4, cex = 0.80,
     bquote(paste("Test for subgroup differences: ",
                  "Chi"^2, " = ", .(fmtx(0.27, digits = 2)),
                  ", df = ", 1,
                  " (", italic(p), .(p_subgroup_diff_data), ")")))

# Add label for axes
text(log(c(0.1, 10)), -5, c("Favours combination of SGLT-2 inhibitor and GLP-1 RA",
                            "Favours SGLT-2 inhibitor or GLP-1 RA monotherapy"),
     pos = c(4,2), offset = -7, cex = 0.80)

# Close PNG device
dev.off()