#' Simple ROC curve with optimal threshold and AUC approximation
#'
#' \code{ROCplot(predictions, truth, N = 100, nulline = TRUE,...)}
#'
#' @param predictions is prediction values between 0 and 1
#' @param truth the actual 0 and 1 values
#' @param N number of candidate thresholds; default is 100
#' @param nulline whether to plot a line with slope=1
#' @param ... additional arguments passed to plot
#'
#' @details Plots a ROC curve. Also gives optimal cut point (several if
#' they are equal in effectiveness) and area under the curve by the
#' trapezoid method, so accuracy improves with greater N.
ROCplot = function(predictions, truth, N = 100, nullline = TRUE,...){
Sens = Spec = Acc = numeric(N+1)
for(a in 0:N){
T = table(factor(as.numeric(predictions>(a/N)),levels=0:1),
factor(truth))
Sens[a+1] = T[2,2]/sum(T[,2])
Spec[a+1] = T[1,1]/sum(T[,1])
Acc[a+1] = sum(diag(T))/sum(T)
}
plot(Spec,Sens,type="l", xlim=1:0, asp = 1,...)
if(nullline==TRUE)abline(1,-1,lty=2)
mx = which(Acc == max(Acc))
span = 0:N/N
cutoffs = span
mxcutoff = cutoffs[mx]
cat("\n", "optimal cut point is: ",mxcutoff, "\n")
H = hist(Sens, breaks = span, plot = FALSE)$counts
# calculate area under curve using trapezoidal method
# areas of triangle and rectangle between adjacent points
DX = c(0,diff(Sens))
DY = c(0,diff(Spec))
DY1 = c(0,DY)[1:length(DY)]
cat("\n", "approx area under curve: ",
sum(DX*DY/2 + Sens*DY1), "\n")
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.