library(tidyverse)
## Warning: package 'tidyverse' was built under R version 3.3.3
## Loading tidyverse: ggplot2
## Loading tidyverse: tibble
## Loading tidyverse: tidyr
## Loading tidyverse: readr
## Loading tidyverse: purrr
## Loading tidyverse: dplyr
## Warning: package 'purrr' was built under R version 3.3.3
## Conflicts with tidy packages ----------------------------------------------
## filter(): dplyr, stats
## lag():    dplyr, stats
dat3 <-
  read.csv('all_indices_truncated.csv') %>% 
  select(BQI,AMBI_S,AMBI,TBI,mud) %>% 
  mutate (mud_binary = cut(mud, breaks = c(0,25,100),labels = c(0,1))) %>% 
  drop_na()

####ROC curves####
library(ROCR)
## Warning: package 'ROCR' was built under R version 3.3.3
## Loading required package: gplots
## Warning: package 'gplots' was built under R version 3.3.3
## 
## Attaching package: 'gplots'
## The following object is masked from 'package:stats':
## 
##     lowess
opt.cut = function(perf, pred){
  cut.ind = mapply(FUN=function(x, y, p){
    d = (x - 0)^2 + (y-1)^2
    ind = which(d == min(d))
    c(sensitivity = y[[ind]], specificity = 1-x[[ind]], 
      cutoff = p[[ind]])
  }, perf@x.values, perf@y.values, pred@cutoffs)
}

pred<- prediction(dat3$AMBI_S,dat3$mud_binary)
roc.perf  <- performance(pred, measure = "tpr", x.measure = "fpr")
print(opt.cut(roc.perf, pred))
##                  [,1]
## sensitivity 0.7333333
## specificity 0.7525253
## cutoff      2.1376028
auc.perf <-  performance(pred, measure = "auc")
auc.perf@y.values
## [[1]]
## [1] 0.8202955
plot(roc.perf, colorize=T)
abline(a=0, b= 1,lty=2)

perf <- performance(pred, "prec", "rec")
plot(perf, colorize=T)