1. Business Questions

The increasing prevalence of mental health issues among employees, exacerbated by the COVID-19 pandemic and the shift to remote work, has raised concerns about the well-being of the workforce. Employers are now faced with the challenge of understanding the factors that contribute to mental health issues and identifying effective interventions to support their employees.

Key questions:

  1. What are some of the main roots causes of an employee’ mental well-being in workplace?

  2. What can company do to improve workplace for the people?

  3. Can I use employees’ survey data to predict whether they sought mental health treatment in the past?

2. Load Data & Libraries

2.1 Import dataset

library(readr)
df <- read_csv("/Users/longnguyen/Downloads/survey.csv") #this is the main data
## Rows: 1259 Columns: 27
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr  (25): Gender, Country, state, self_employed, family_history, treatment,...
## dbl   (1): Age
## dttm  (1): Timestamp
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
# View(survey)

2.2 Import libraries

library(dplyr) # used for data manipulation and data cleaning
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(tidyr) # data manipulation
library(ggplot2) # visualization
library(caret) # machine learning (classification), feature importance
## Loading required package: lattice
library(corrplot) # correlation
## corrplot 0.92 loaded
library(mlbench) # machine learning
library(randomForest)
## randomForest 4.7-1.1
## Type rfNews() to see new features/changes/bug fixes.
## 
## Attaching package: 'randomForest'
## The following object is masked from 'package:ggplot2':
## 
##     margin
## The following object is masked from 'package:dplyr':
## 
##     combine
library(rpart) # regression trees
library(rpart.plot) # regression plot
library(e1071) # SVM
library(pROC) # AUC
## Type 'citation("pROC")' for a citation.
## 
## Attaching package: 'pROC'
## The following objects are masked from 'package:stats':
## 
##     cov, smooth, var

2.3 First look at data

dim(df)
## [1] 1259   27

COMMENT: There are 1259 observations and 27 columns.

summary(df)
##    Timestamp                        Age                Gender         
##  Min.   :2014-08-27 11:29:31   Min.   :-1.726e+03   Length:1259       
##  1st Qu.:2014-08-27 14:26:56   1st Qu.: 2.700e+01   Class :character  
##  Median :2014-08-28 02:30:00   Median : 3.100e+01   Mode  :character  
##  Mean   :2014-09-10 00:15:52   Mean   : 7.943e+07                     
##  3rd Qu.:2014-08-28 23:36:48   3rd Qu.: 3.600e+01                     
##  Max.   :2016-02-01 23:04:31   Max.   : 1.000e+11                     
##    Country             state           self_employed      family_history    
##  Length:1259        Length:1259        Length:1259        Length:1259       
##  Class :character   Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character   Mode  :character  
##                                                                             
##                                                                             
##                                                                             
##   treatment         work_interfere     no_employees       remote_work       
##  Length:1259        Length:1259        Length:1259        Length:1259       
##  Class :character   Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character   Mode  :character  
##                                                                             
##                                                                             
##                                                                             
##  tech_company         benefits         care_options       wellness_program  
##  Length:1259        Length:1259        Length:1259        Length:1259       
##  Class :character   Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character   Mode  :character  
##                                                                             
##                                                                             
##                                                                             
##   seek_help          anonymity            leave          
##  Length:1259        Length:1259        Length:1259       
##  Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character  
##                                                          
##                                                          
##                                                          
##  mental_health_consequence phys_health_consequence  coworkers        
##  Length:1259               Length:1259             Length:1259       
##  Class :character          Class :character        Class :character  
##  Mode  :character          Mode  :character        Mode  :character  
##                                                                      
##                                                                      
##                                                                      
##   supervisor        mental_health_interview phys_health_interview
##  Length:1259        Length:1259             Length:1259          
##  Class :character   Class :character        Class :character     
##  Mode  :character   Mode  :character        Mode  :character     
##                                                                  
##                                                                  
##                                                                  
##  mental_vs_physical obs_consequence      comments        
##  Length:1259        Length:1259        Length:1259       
##  Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character  
##                                                          
##                                                          
## 
column_types <- sapply(df, class)

# Count the number of categorical and numerical columns
num_categorical <- sum(column_types == "factor" | column_types == "character")
num_numerical <- sum(column_types == "numeric")

cat("There are",num_categorical,"categorical variables and",num_numerical,"numerical variables.")
## There are 25 categorical variables and 1 numerical variables.

3. Data Cleaning

sum(is.na(df)) # Ouch, guess a lot of data cleaning we have to do!
## [1] 1893

3.1 Age

# Numerical variable - Age
ggplot(df, aes(x=Age)) + geom_boxplot() # Visualize the distribution of numeric value: age

table(df$Age)
## 
##       -1726         -29          -1           5           8          11 
##           1           1           1           1           1           1 
##          18          19          20          21          22          23 
##           7           9           6          16          21          51 
##          24          25          26          27          28          29 
##          46          61          75          71          68          85 
##          30          31          32          33          34          35 
##          63          67          82          70          65          55 
##          36          37          38          39          40          41 
##          37          43          39          33          33          21 
##          42          43          44          45          46          47 
##          20          28          11          12          12           2 
##          48          49          50          51          53          54 
##           6           4           6           5           1           3 
##          55          56          57          58          60          61 
##           3           4           3           1           2           1 
##          62          65          72         329 99999999999 
##           1           1           1           1           1

COMMENT: The boxplot for numeric Age column is not showning. As seen above, there are extreme outliers from both ends.

df <- df %>% filter(Age >= 0, Age <= 100) # only retain employees with age range from 0 to 100
ggplot(df, aes(x=Age)) + geom_boxplot()

3.2 Gender

COMMENT: In order to do EDA, I need to keep unique value counts for Gender consistent.

# Gender column
df$Gender <- gsub('^(Male |male|M|m|Male|Cis Male|Man|cis male|Mail|Male-ish|Male \\(CIS\\)|Cis Man|msle|Malr|Mal|maile|Make)$', 'Male', df$Gender)
df$Gender <- gsub('^(Female |female|F|f|Woman|Female|femail|Cis Female|cis-female/femme|Femake|Female \\(cis\\)|woman)$', 'Female', df$Gender)
df$Gender <- gsub('^(Female \\(trans\\)|queer/she/they|non-binary|fluid|queer|Androgyne|Trans-female|male leaning androgynous|Agender|A little about you|Nah|All|ostensibly male, unsure what that really means|Genderqueer|Enby|p|Neuter|something kinda male\\?|Guy \\(-ish\\) \\^_\\^|Trans woman)$', 'Other', df$Gender)

table(df$Gender)
## 
## Female   Male  Other 
##    247    988     19
ggplot(df,aes(x=Gender, fill=Gender)) + geom_bar()

3.3 Handling NA values

# NA values ?
sapply(df, function(x) sum(is.na(x)))
##                 Timestamp                       Age                    Gender 
##                         0                         0                         0 
##                   Country                     state             self_employed 
##                         0                       513                        18 
##            family_history                 treatment            work_interfere 
##                         0                         0                       263 
##              no_employees               remote_work              tech_company 
##                         0                         0                         0 
##                  benefits              care_options          wellness_program 
##                         0                         0                         0 
##                 seek_help                 anonymity                     leave 
##                         0                         0                         0 
## mental_health_consequence   phys_health_consequence                 coworkers 
##                         0                         0                         0 
##                supervisor   mental_health_interview     phys_health_interview 
##                         0                         0                         0 
##        mental_vs_physical           obs_consequence                  comments 
##                         0                         0                      1092

COMMENT: There are NA values in 4 columns: state, self_employed, work_interfere, and comments.

# remove columns
df <- df %>% select(-state, -comments)

COMMENT: For my analysis, I assumed that state and comments are irrelevant in classfication. Moving to dealing with NA values in self_employed and work_interfere.

In this project, I will take the approach of replace NA values with mode of each feature.

# names(table(df$work_interfere)[which.max(table(df$work_interfere))])
# create mode replacing function
mode_sub <- function(x) {
  mode_value <- names(table(x)[which.max(table(x))]) # find the max freq value - mode
  x[is.na(x)] <- mode_value
  return(x)
}

# modify df
df[c("work_interfere", "self_employed")] <- df[c("work_interfere", "self_employed")] %>% sapply(mode_sub)

4. Exploratory Data Analysis

I will be focusing on performing visualization with regard to dependent variable - treatment.

4.1 Bivariate

4.1.1 Age vs treatment

ggplot(df,aes(x=Age,fill=treatment)) + geom_bar()

4.1.2 Gender vs treatment

ggplot(df, aes(x = Gender, fill = treatment)) +
  geom_bar(position = "fill") +
  geom_text(
    aes(label = paste0(..count.., " (", signif(100*..count.. / tapply(..count.., ..x.., sum)[as.character(..x..)], digits = 3), "%)")),
    stat = "count",
    position = position_fill(vjust = 0.5),
    vjust = -0.5,
    size = 3 
  ) +
  labs(y = "Count (Percentage)")
## Warning: The dot-dot notation (`..count..`) was deprecated in ggplot2 3.4.0.
## ℹ Please use `after_stat(count)` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.

4.1.3 Do people feel that mental health problems interfere with their work?

ggplot(df, aes(x=factor(work_interfere,levels=c("Never", "Rarely", "Sometimes", "Often")), fill=treatment)) +
  geom_bar(position = "fill") +
  geom_text(
    aes(label = paste0(..count.., " (", signif(100*..count.. / tapply(..count.., ..x.., sum)[as.character(..x..)], digits = 3), "%)")),
    stat = "count",
    position = position_fill(vjust = 0.5),
    vjust = -0.5,
    size = 3 
  ) +
  labs(x="Do people feel mental health issues affect work?",y="Count (Percentage)")

4.1.4 Do people have a family history of mental illness?

ggplot(df, aes(x=family_history, fill=treatment)) +
  geom_bar(position = "fill") +
  geom_text(
    aes(label = paste0(..count.., " (", signif(100*..count.. / tapply(..count.., ..x.., sum)[as.character(..x..)], digits = 3), "%)")),
    stat = "count",
    position = position_fill(vjust = 0.5),
    vjust = -0.5,
    size = 3 
  ) +
  labs(x="Family history",y="Count (Percentage)")

4.1.5 Do people work remotely?

ggplot(df, aes(x=remote_work, fill=treatment)) +
  geom_bar(position="fill") +
  geom_text(
    aes(label=signif(100*..count.. / tapply(..count.., ..x.., sum)[as.character(..x..)], digits=3)),
    stat="count",
    position=position_fill(vjust=0.5)) +
  labs(x="Remote work",y="Percentage (%)")

4.1.6 Do people find it easy for medical leave?

ggplot(df, aes(x=factor(leave, levels = c("Don't know","Very easy","Somewhat easy","Somewhat difficult", "Very difficult")), fill=treatment)) +
  geom_bar(position = "fill") +
  geom_text(
    aes(label = paste0(..count.., " (", signif(100*..count.. / tapply(..count.., ..x.., sum)[as.character(..x..)], digits = 3), "%)")),
    stat = "count",
    position = position_fill(vjust = 0.5),
    vjust = -0.5,
    size = 3 
  ) +
  labs(x="Medical leave for mental health issues?",y="Percentage (%)")

4.1.7 Does company size affect one’s mental health?

# Define the custom order
custom_order <- c("1-5", "6-25", "26-100", "100-500", "500-1000", "More than 1000")

# plot
ggplot(df, aes(x = factor(no_employees, levels = custom_order), fill = treatment)) + geom_bar(position="fill") +
  geom_bar(position = "fill") +
  geom_text(
    aes(label = paste0(..count.., " (", signif(100*..count.. / tapply(..count.., ..x.., sum)[as.character(..x..)], digits = 3), "%)")),
    stat = "count",
    position = position_fill(vjust = 0.5),
    vjust = -0.5,
    size = 3 
  ) +
  labs(x="Company size",y="Percentage (%)")

4.1.8 Do people think discussing mental health consequences with employers would have negative consequences?

ggplot(df, aes(x=mental_health_consequence, fill=treatment)) +
  geom_bar(position = "fill") +
  geom_text(
    aes(label = paste0(..count.., " (", signif(100*..count.. / tapply(..count.., ..x.., sum)[as.character(..x..)], digits = 3), "%)")),
    stat = "count",
    position = position_fill(vjust = 0.5),
    vjust = -0.5,
    size = 3 
  ) +
  labs(x="Is discussing mental health issue with employer would have negative consequences?",y="Percentage (%)")

4.1.9 Does employer provide resources to learn more about mental health issues and how to seek help?

ggplot(df, aes(x=seek_help, fill=treatment)) +
  geom_bar(position = "fill") +
  geom_text(
    aes(label = paste0(..count.., " (", signif(100*..count.. / tapply(..count.., ..x.., sum)[as.character(..x..)], digits = 3), "%)")),
    stat = "count",
    position = position_fill(vjust = 0.5),
    vjust = -0.5,
    size = 3 
  ) +
  labs(x="Does employer provide resources to seek help and mental health support?",y="Percentage (%)")

4.1.10 Does employer provide mental health benefits?

ggplot(df,aes(x=benefits,fill=treatment)) + geom_bar()

4.1.11 Do you know the options for mental health care your employer provides?

# physical
ggplot(df, aes(x=care_options, fill=treatment)) +
  geom_bar(position = "fill") +
  geom_text(
    aes(label = paste0(..count.., " (", signif(100*..count.. / tapply(..count.., ..x.., sum)[as.character(..x..)], digits = 3), "%)")),
    stat = "count",
    position = position_fill(vjust = 0.5),
    vjust = -0.5,
    size = 3 
  ) +
  labs(x="Awareness of mental health care options provided by company?",y="Percentage (%)")

5. Feature engineering

5.1 Factor conversion

Before encoding categorical variables, I will drop Timestamp, Country.

df <- df %>% select(-Timestamp, -Country)

5.1.1 Independent variables

To start encoding, I need to create a list of unique values in order

# list out unique values of each categorical variables I will be using for modeling <- encoding
cols <- list(
  Gender = c('Male', 'Female', 'Other'),
  self_employed = c('No', 'Yes'),
  family_history = c('No', 'Yes'),
  work_interfere = c('Never', 'Rarely', 'Sometimes', 'Often'),
  no_employees = c('1-5', '6-25', '26-100', '100-500', '500-1000', 'More than 1000'),
  remote_work = c('No', 'Yes'),
  tech_company = c('No', 'Yes'),
  benefits = c('No', 'Don\'t know', 'Yes'),
  care_options = c('No', 'Not sure', 'Yes'),
  wellness_program = c('No', 'Don\'t know', 'Yes'),
  seek_help = c('No', 'Don\'t know', 'Yes'),
  anonymity = c('No', 'Don\'t know', 'Yes'),
  leave = c('Very easy', 'Somewhat easy', 'Don\'t know', 'Somewhat difficult', 'Very difficult'),
  mental_health_consequence = c('No', 'Maybe', 'Yes'),
  phys_health_consequence = c('No', 'Maybe', 'Yes'),
  coworkers = c('No', 'Some of them', 'Yes'),
  supervisor = c('No', 'Some of them', 'Yes'),
  mental_health_interview = c('No', 'Maybe', 'Yes'),
  phys_health_interview = c('No', 'Maybe', 'Yes'),
  mental_vs_physical = c('Don\'t know', 'No', 'Yes'),
  obs_consequence = c('No', 'Yes')
)

Now, I encode all the independent variables:

for (col_name in names(cols)) {
  df[[col_name]] <- factor(df[[col_name]], levels = cols[[col_name]])
}

5.1.2 Dependent variable

# treatment 
df$treatment <- as.factor(df$treatment)

5.2 Feature importance

I want to perform feature selection using Chi Square test to see if there’re any association between all categorical variables and target variable treatment. \(\alpha\) = 0.05 (default).

\(H_0\): There’s no association between predictor categorical variable and treatment

\(H_a\): There’s an association between predictor categorical variable and treatment

# Create an empty data frame to store results
result_df <- data.frame(Variable = character(), P_Value = numeric(), stringsAsFactors = FALSE)

# Iterate
for (var_name in names(cols)) {
  # chi sq test on each categorical var
  chisq_result <- chisq.test(table(df[[var_name]], df$treatment))
  
  # Store variable names and respective p values into result_df
  result_df <- rbind(result_df, data.frame(var = var_name, pval = chisq_result$p.value))
}

# Filter 
significant_vars <- result_df[result_df$pval <= 0.05, ] # statistical significance
significant_vars
##                          var         pval
## 1                     Gender 1.503599e-11
## 3             family_history 1.543585e-40
## 4             work_interfere 6.175150e-45
## 8                   benefits 8.850146e-15
## 9               care_options 6.296769e-21
## 10          wellness_program 4.096879e-03
## 11                 seek_help 3.926880e-03
## 12                 anonymity 2.239818e-06
## 13                     leave 8.093187e-06
## 14 mental_health_consequence 2.767354e-05
## 16                 coworkers 4.543873e-02
## 18   mental_health_interview 2.399683e-03
## 20        mental_vs_physical 2.217226e-04
## 21           obs_consequence 6.952363e-08
# filter chosen columns 
df <- df %>% select(significant_vars$var,'treatment')

5.3 Class imbalance

table(df$treatment)
## 
##  No Yes 
## 621 633
ggplot(df,aes(x=treatment,fill=treatment)) + geom_bar()

COMMENT: No need to worry about class imbalance!

5.4 Train-test split

# Split the data into training and testing sets. Set seed for reproducible
set.seed(42)
train_index <- createDataPartition(df$treatment, p = 0.8, list = FALSE)
train_data <- df[train_index, ]
test_data <- df[-train_index, ]
levels(train_data$treatment)
## [1] "No"  "Yes"

6. Models - binary classification: treatment - “No”, “Yes”

6.1 Logistic regression

# Logistic Regression
model_1 <- glm(treatment ~ ., family = binomial, data = train_data)
summary(model_1)
## 
## Call:
## glm(formula = treatment ~ ., family = binomial, data = train_data)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.6153  -0.8008   0.1893   0.8065   2.7103  
## 
## Coefficients:
##                                 Estimate Std. Error z value Pr(>|z|)    
## (Intercept)                    -3.720898   0.564848  -6.587 4.48e-11 ***
## GenderFemale                    0.573891   0.205381   2.794  0.00520 ** 
## GenderOther                     1.149828   0.743799   1.546  0.12213    
## family_historyYes               1.303152   0.163925   7.950 1.87e-15 ***
## work_interfereRarely            2.150343   0.318109   6.760 1.38e-11 ***
## work_interfereSometimes         1.534815   0.259906   5.905 3.52e-09 ***
## work_interfereOften             3.465879   0.386192   8.974  < 2e-16 ***
## benefitsDon't know             -0.123159   0.233808  -0.527  0.59837    
## benefitsYes                     0.340939   0.237167   1.438  0.15056    
## care_optionsNot sure           -0.091803   0.209932  -0.437  0.66190    
## care_optionsYes                 0.859455   0.215360   3.991 6.59e-05 ***
## wellness_programDon't know      0.066821   0.257272   0.260  0.79507    
## wellness_programYes            -0.161577   0.272543  -0.593  0.55328    
## seek_helpDon't know             0.416571   0.223611   1.863  0.06247 .  
## seek_helpYes                    0.130185   0.282872   0.460  0.64535    
## anonymityDon't know             0.245477   0.383304   0.640  0.52190    
## anonymityYes                    0.535519   0.411270   1.302  0.19288    
## leaveSomewhat easy             -0.332340   0.266776  -1.246  0.21285    
## leaveDon't know                -0.064642   0.248015  -0.261  0.79437    
## leaveSomewhat difficult         0.436165   0.341974   1.275  0.20216    
## leaveVery difficult             0.399784   0.386259   1.035  0.30066    
## mental_health_consequenceMaybe  0.448478   0.203857   2.200  0.02781 *  
## mental_health_consequenceYes    0.684682   0.265554   2.578  0.00993 ** 
## coworkersSome of them           0.473803   0.213364   2.221  0.02638 *  
## coworkersYes                    0.936617   0.294938   3.176  0.00150 ** 
## mental_health_interviewMaybe   -0.457600   0.236401  -1.936  0.05290 .  
## mental_health_interviewYes      0.258574   0.456895   0.566  0.57144    
## mental_vs_physicalNo            0.016133   0.206216   0.078  0.93764    
## mental_vs_physicalYes          -0.004828   0.215780  -0.022  0.98215    
## obs_consequenceYes              0.222576   0.243772   0.913  0.36121    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 1391.7  on 1003  degrees of freedom
## Residual deviance: 1003.6  on  974  degrees of freedom
## AIC: 1063.6
## 
## Number of Fisher Scoring iterations: 5
# Make prediction on the test dataset
p1 <- predict(model_1, test_data,type='response')
predicted_labels <- ifelse(p1 > 0.5, "Yes", "No")
# Calculate the final accuracy
result1 = sum(factor(predicted_labels)==test_data$treatment)/nrow(test_data)
print(paste("Final Accuracy =",sprintf("%1.2f%%", 100*result1)))
## [1] "Final Accuracy = 76.80%"
confusionMatrix(factor(predicted_labels),test_data$treatment)
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction No Yes
##        No  98  32
##        Yes 26  94
##                                           
##                Accuracy : 0.768           
##                  95% CI : (0.7107, 0.8189)
##     No Information Rate : 0.504           
##     P-Value [Acc > NIR] : <2e-16          
##                                           
##                   Kappa : 0.5361          
##                                           
##  Mcnemar's Test P-Value : 0.5115          
##                                           
##             Sensitivity : 0.7903          
##             Specificity : 0.7460          
##          Pos Pred Value : 0.7538          
##          Neg Pred Value : 0.7833          
##              Prevalence : 0.4960          
##          Detection Rate : 0.3920          
##    Detection Prevalence : 0.5200          
##       Balanced Accuracy : 0.7682          
##                                           
##        'Positive' Class : No              
## 
auc1 <- multiclass.roc(as.numeric(test_data$treatment), as.numeric(as.factor(p1)))
## Setting direction: controls < cases
auc1
## 
## Call:
## multiclass.roc.default(response = as.numeric(test_data$treatment),     predictor = as.numeric(as.factor(p1)))
## 
## Data: as.numeric(as.factor(p1)) with 2 levels of as.numeric(test_data$treatment): 1, 2.
## Multi-class area under the curve: 0.8405

6.2 Decision tree

# Fit the model on the train dataset
tree <- rpart(treatment ~ ., test_data)
pruned_tree <- prune(tree, cp = 0.01)  # Adjust the complexity parameter as needed
rpart.plot(pruned_tree, extra = 104, under = TRUE, varlen = 0, faclen = 0)

p2 <- predict(tree, test_data, type="class")
head(p2)
##   1   2   3   4   5   6 
## Yes  No Yes  No  No  No 
## Levels: No Yes
result2 <- sum(p2==test_data$treatment)/nrow(test_data)
cat(paste("Final Accuracy =",sprintf("%1.2f%%", 100*result2)))
## Final Accuracy = 79.20%
confusionMatrix(p2,test_data$treatment)
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  No Yes
##        No  101  29
##        Yes  23  97
##                                           
##                Accuracy : 0.792           
##                  95% CI : (0.7364, 0.8406)
##     No Information Rate : 0.504           
##     P-Value [Acc > NIR] : <2e-16          
##                                           
##                   Kappa : 0.5841          
##                                           
##  Mcnemar's Test P-Value : 0.4881          
##                                           
##             Sensitivity : 0.8145          
##             Specificity : 0.7698          
##          Pos Pred Value : 0.7769          
##          Neg Pred Value : 0.8083          
##              Prevalence : 0.4960          
##          Detection Rate : 0.4040          
##    Detection Prevalence : 0.5200          
##       Balanced Accuracy : 0.7922          
##                                           
##        'Positive' Class : No              
## 
auc2 <- multiclass.roc(as.numeric(test_data$treatment), as.numeric(as.factor(p2)))
## Setting direction: controls < cases
auc2
## 
## Call:
## multiclass.roc.default(response = as.numeric(test_data$treatment),     predictor = as.numeric(as.factor(p2)))
## 
## Data: as.numeric(as.factor(p2)) with 2 levels of as.numeric(test_data$treatment): 1, 2.
## Multi-class area under the curve: 0.7922

6.3 Random forest

model_2 <- randomForest(treatment ~ ., data = train_data, n.trees = 10, interaction.depth = 5)
# Make prediction on the test dataset
p3 <- predict(model_2, test_data)
head(p3)
##   1   2   3   4   5   6 
## Yes  No Yes  No  No  No 
## Levels: No Yes
# Calculate the final accuracy
result3 <- sum(p3==test_data$treatment)/nrow(test_data)
cat(paste("Final Accuracy =",sprintf("%1.2f%%", 100*result3)))
## Final Accuracy = 76.80%
confusionMatrix(p3,test_data$treatment)
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  No Yes
##        No  102  36
##        Yes  22  90
##                                           
##                Accuracy : 0.768           
##                  95% CI : (0.7107, 0.8189)
##     No Information Rate : 0.504           
##     P-Value [Acc > NIR] : < 2e-16         
##                                           
##                   Kappa : 0.5364          
##                                           
##  Mcnemar's Test P-Value : 0.08783         
##                                           
##             Sensitivity : 0.8226          
##             Specificity : 0.7143          
##          Pos Pred Value : 0.7391          
##          Neg Pred Value : 0.8036          
##              Prevalence : 0.4960          
##          Detection Rate : 0.4080          
##    Detection Prevalence : 0.5520          
##       Balanced Accuracy : 0.7684          
##                                           
##        'Positive' Class : No              
## 
auc3 <- multiclass.roc(as.numeric(test_data$treatment), as.numeric(as.factor(p3)))
## Setting direction: controls < cases
auc3
## 
## Call:
## multiclass.roc.default(response = as.numeric(test_data$treatment),     predictor = as.numeric(as.factor(p3)))
## 
## Data: as.numeric(as.factor(p3)) with 2 levels of as.numeric(test_data$treatment): 1, 2.
## Multi-class area under the curve: 0.7684

6.4 SVM

svm_classifier <- svm(formula = treatment ~ ., 
                      data = train_data, 
                      type = 'C-classification', 
                      kernel = 'linear') 
svm_classifier
## 
## Call:
## svm(formula = treatment ~ ., data = train_data, type = "C-classification", 
##     kernel = "linear")
## 
## 
## Parameters:
##    SVM-Type:  C-classification 
##  SVM-Kernel:  linear 
##        cost:  1 
## 
## Number of Support Vectors:  589
p4 <- predict(svm_classifier,newdata = test_data)
head(p4)
##   1   2   3   4   5   6 
## Yes  No Yes  No  No  No 
## Levels: No Yes
# Calculate the final accuracy
result4 <- sum(p4==test_data$treatment)/nrow(test_data)
cat(paste("Final Accuracy =",sprintf("%1.2f%%", 100*result4)))
## Final Accuracy = 78.00%
confusionMatrix(p4,test_data$treatment)
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  No Yes
##        No  102  33
##        Yes  22  93
##                                           
##                Accuracy : 0.78            
##                  95% CI : (0.7235, 0.8298)
##     No Information Rate : 0.504           
##     P-Value [Acc > NIR] : <2e-16          
##                                           
##                   Kappa : 0.5603          
##                                           
##  Mcnemar's Test P-Value : 0.1775          
##                                           
##             Sensitivity : 0.8226          
##             Specificity : 0.7381          
##          Pos Pred Value : 0.7556          
##          Neg Pred Value : 0.8087          
##              Prevalence : 0.4960          
##          Detection Rate : 0.4080          
##    Detection Prevalence : 0.5400          
##       Balanced Accuracy : 0.7803          
##                                           
##        'Positive' Class : No              
## 
auc4 <- multiclass.roc(as.numeric(test_data$treatment), as.numeric(as.factor(p4)))
## Setting direction: controls < cases
auc4
## 
## Call:
## multiclass.roc.default(response = as.numeric(test_data$treatment),     predictor = as.numeric(as.factor(p4)))
## 
## Data: as.numeric(as.factor(p4)) with 2 levels of as.numeric(test_data$treatment): 1, 2.
## Multi-class area under the curve: 0.7803