简体   繁体   中英

Plot multiple ROC curves using a for loop

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)

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()               }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM