---
title: "Alzheimer Study Demographics (N = 254)"
output: 
  flexdashboard::flex_dashboard
---

```{r setup, include = FALSE}
library(flexdashboard)
library(ggplot2)
adsl <- read.csv("adsl.txt")
```


Categorical {data-icon="fa-bar-chart"}
===================================== 

Column 1
---

### <font color = "black" size = "3" > Percentage Bar Charts for Sex, Race and Age </font>


```{r, include = TRUE, echo = FALSE}

df <- adsl[, c("STUDYID", "USUBJID", "SUBJID", "ARM",
               "AGE", "AGEGR1", "AGEGR1N", "AGEU", "RACE",
               "RACEN", "SEX", "ETHNIC", "BMIBL", "BMIBLGR1",
               "HEIGHTBL", "WEIGHTBL", "EDUCLVL", "DISONSDT",
               "DURDIS")]


# Calculate the percentages for the categorical variables
sex_percent <- table(df$SEX)/nrow(df)*100
race_percent <- table(df$RACE)/nrow(df)*100
age_percent <- table(df$AGEGR1)/nrow(df)*100


# Create data-frame for categorical variables
percents <- round(c(sex_percent, race_percent, age_percent), 1)
percent_labs <- format(percents, nsmall = 1) #Percentage text for plot


cat_vars <- c(rep("Sex", 2), 
               rep("Race", 3),
               rep("Age Group (years)", 3))

cats <- c("Female", "Male", 
          "AI or AN", "B or AA", "White",
          "< 65", "> 80", "65 - 80")

cat_df <- data.frame(percents = percents, 
                     cat_vars = cat_vars,
                     cats = cats,
                     percent_labs = percent_labs)


# Reorder cat_vars and cats
cat_df$cat_vars = factor(cat_df$cat_vars, 
                  levels = c("Sex", 
                            "Race", 
                            "Age Group (years)"))

cat_df$cats =  factor(cat_df$cats, 
               levels = c("Male", "Female",
                          "White", "B or AA", "AI or AN", 
                          "< 65", "65 - 80", "> 80"))


# Choose colors for each of the 6 plots (3 also for the continuous plots)
gg_color_hue <- function(n) {
  hues = seq(15, 375, length = n + 1)
  hcl(h = hues, l = 65, c = 100)[1:n]
}

cols <- gg_color_hue(6)


# Produce the bar chart for the categorical variables
ggplot(data = cat_df) + 
  geom_bar(aes(x = cats, y = percents, fill = cat_vars), 
           stat = 'identity') + ylim(0, 100) +
  facet_grid(~ cat_vars, scales = "free_x") + 
  
  scale_fill_manual(values = c("Sex" = cols[1],
                               "Race" = cols[2],
                               "Age Group (years)" = cols[3])) +

  theme(panel.grid.minor = element_blank(),
        panel.grid.major.x = element_blank(),
        panel.grid.major.y = element_line(color = 'white'),
        legend.position = 'none',
        panel.background = element_rect(fill = 'gray96'),
        strip.text.x = element_text(size = 9),
        strip.background = element_rect(fill = 'gray88'),
        plot.title = element_text(hjust = 0.5, size = 13),
        panel.spacing = unit(1.2, "lines"),
        axis.title.y = element_text(margin = margin(r = 5))) +
  
  labs(x = '', 
       y = 'Percentage (%)',
       caption = "B or AA = Black or African American;  AI or AN = American Indian or Alaska Native.
       
                  Author: Huw Wilson") +
  
  geom_text(stat = 'identity', 
            aes(x = cats, y = percents, label = percent_labs),
            vjust = -0.4)

```


Column 2
---

### Commentary
<br>
From the graph, we can see that there are relatively equal numbers of men and women (43.7% and 56.3%, respectively).<br> <br>
The population is majority white (90.6%) while 9.1% and 0.4% are Black or African American and American Indian or Alaska Native, respectively.
<br><br>
The study participants also skew older with 87% being over the age of 65 and 30.3% being over the age of 80.


Continuous {data-icon="fa-area-chart"}
=====================================


Column 1
------------------------------------------

### <font color = "black" size = "3"> Density Plots with Medians for BMI, Education and Disease Duration </font>

```{r, include = TRUE, echo = FALSE}

# Convert disease duration from months to years
durdis <- df$DURDIS/12

bmi <- na.omit(as.numeric(df$BMIBL)) #One NA value in BMI
edu <- df$EDUCLVL

# Find median for each variable
med_durdis <- median(durdis)
med_bmi <- median(bmi)
med_edu <- median(edu)

meds <- c(med_bmi, med_edu, med_durdis)
meds_c <- format(round(meds, 1), nsmall = 1) # Median text for plot


# Dataframe containing the variable medians
med_df <- data.frame(x1 = c(med_bmi, med_edu, med_durdis),
                     x2 = c(med_bmi, med_edu, med_durdis),
                     y1 = c(0, 0, 0),
                     y2 = c(0.25, 0.25, 0.25),
                     meds_c = meds_c,
                     cont_vars = c("BMI (kg/m^2)*",
                                   "Education Level (years)",
                                   "Disease Duration (years)"))

med_df$cont_vars <- factor(med_df$cont_vars,
                            levels = c("BMI (kg/m^2)*", 
                                       "Education Level (years)",
                                       "Disease Duration (years)"))


# Create dataframe for continuous variables
cont_vals <- c(durdis, edu, bmi) 

cont_vars <- c(rep(c("Disease Duration (years)",
                     "Education Level (years)"), each = 254),
               rep("BMI (kg/m^2)*", 253))

cont_df <- data.frame(cont_vals = cont_vals, 
                      cont_vars = cont_vars)

# Re-order cont_vars
cont_df$cont_vars <- factor(cont_df$cont_vars,
                     levels = c("BMI (kg/m^2)*", 
                               "Education Level (years)",
                               "Disease Duration (years)"))


# Produce density plot for continuous variables
ggplot(data = cont_df) +
            geom_density(aes(x = cont_vals, 
                             fill = cont_vars, 
                             color = cont_vars),
                        adjust = 1.25) + ylim(0, 0.3) +
  
            facet_grid(~cont_vars, scales = "free") +
  
            scale_fill_manual(
              values = c("BMI (kg/m^2)*" = cols[4],
                         "Education Level (years)" = cols[5],
                        "Disease Duration (years)" = cols[6])) +
  
            scale_color_manual(
              values = c("BMI (kg/m^2)*" = cols[4], 
                         "Education Level (years)" = cols[5],
                         "Disease Duration (years)" = cols[6])) +
  
            theme(panel.grid.minor = element_blank(),
            panel.grid.major.x = element_blank(),
            panel.grid.major.y = element_line(color = 'white'),
            legend.position = 'none',
            panel.background = element_rect(fill = 'gray96'),
            strip.text.x = element_text(size = 9),
            strip.background = element_rect(fill = 'gray88'),
            panel.spacing = unit(1.2, "lines"),
            axis.title.y = element_text(margin = margin(r = 5))) +
  
           labs(x = "", 
                y = "Density", 
                caption = "* Only 253 recorded values for BMI.
                
                           Author: Huw Wilson") +
  
    geom_segment(data = med_df, aes(x = x1, y = y1, xend = x2, yend = y2)) +
  
    geom_text(data = med_df, aes(x = x1, y = y2, label = meds_c), vjust = -0.75)

```



Column 2
-----------------------------------------

### Commentary
<br>
The median BMI of the population is 24.2, and we can see that the majority of participants lie within the 20-30 range.
<br><br>
The median number of years in education is 12, and we can also see slight peaks in the distribution at around 8 and 16 years.
<br><br>
We can see that most participants have been diagnosed with the condition within the last 5 years, with the median number of years since diagnosis being 3.


