Skip to content

Instantly share code, notes, and snippets.

@meyera
Created December 3, 2016 18:08
Show Gist options
  • Save meyera/dc075bb1d8762387a89c4a6261a82a06 to your computer and use it in GitHub Desktop.
Save meyera/dc075bb1d8762387a89c4a6261a82a06 to your computer and use it in GitHub Desktop.
ROC plot and AUC calculation the tidy way - by David Robinson (@drob) tweeted at 5:22 PM on Tue, Nov 29, 2016: Using tidyverse tools to calculate AUC and plot ROC curves #rstats https://t.co/BYJcKXJwoe (https://twitter.com/drob/status/803635156841943040?s=03)
library(tidyverse)
theme_set(theme_minimal())
roc <- iris %>%
gather(Metric, Value, -Species) %>%
mutate(Positive = Species == "virginica") %>%
group_by(Metric, Value) %>%
summarise(Positive = sum(Positive),
Negative = n() - sum(Positive)) %>%
arrange(-Value) %>%
mutate(TPR = cumsum(Positive) / sum(Positive),
FPR = cumsum(Negative) / sum(Negative))
roc %>% group_by(Metric) %>%
summarise(AUC = sum(diff(FPR) * na.omit(lead(TPR) + TPR)) / 2)
ggplot(roc, aes(FPR, TPR, color = Metric, frame = FPR)) +
geom_line() +
geom_abline(lty = 2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment