Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plot multiple ROC curves using a for loop

Tags:

r

ggplot2

I need to plot a number of different ROC curves on a single plot. To avoid manually creating each ROC curve, I have created a for loop that automates this process. However, for some reason, the code only outputs a single curve, for the last model in the list of names. Can anyone help me figure out why its not working? Please see below for a reproducible example:

library(pROC)
library(tidyverse)

dat_tst_2 <- data.frame(result = sample(letters[1:2], 100, replace = T))

preds_1 <- data.frame(x = runif(100),
                      y = runif(100))
preds_2 <- data.frame(x = runif(100),
                      y = runif(100))

names_preds <- c("preds_1", "preds_2")

output <- list()

for (j in 1:length(names_preds)) {
     for (i in names_preds) {
          roc_model <- roc(response = dat_tst_2$result, 
                           predictor = eval(as.name(i))[,2],
                           levels = c("a", "b"),
                           plot = F) 
          output[[j]] <- roc_model
     }   
}

ggroc(output)
like image 600
DJC Avatar asked Apr 25 '26 00:04

DJC


1 Answers

First make sure output has multiple items usin str(output). Then try instead to pass each item in output to ggroc:

 lappy( output, function (out) { png()
                  print (ggroc(out))
                   dev.off()               }
like image 115
IRTFM Avatar answered Apr 27 '26 15:04

IRTFM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!