在R中编写函数,使用pROC绘制ROC曲线



我正试图编写一个函数,根据不同的评分系统绘制ROC曲线,我必须预测结果。

我有一个数据帧data_all,列为"score_1"one_answers"Threshold.2000"。我根据需要生成ROC曲线,如下所示:

plot.roc(data_all$Threshold.2000, data_all$score_1)

我的目标是为许多不同的结果(例如阈值1000(和分数(分数_1、分数_2等(生成ROC曲线,但我最初试图仅为不同的分数设置它。我的功能如下:

roc_plot <- function(dataframe_of_interest, score_of_interest) {
plot.roc(dataframe_of_interest$Threshold.2000, dataframe_of_interest$score_of_interest)}

我得到以下错误:roc.default中的错误(x,预测器,plot=TRUE,…(:未提供有效数据。

如果有人能发现我的功能不起作用的原因,我将不胜感激!我是一个python程序员,也是R的新手,在尝试许多不同的东西时运气不太好。非常感谢。

编辑:以下是mtcars的相同示例,因此它是可复制的:

data(mtcars)
plot.roc(mtcars$vs, mtcars$mpg) # --> makes correct graph
roc_plot <- function(dataframe_of_interest, score_of_interest) {
plot.roc(dataframe_of_interest$mpg, dataframe_of_interest$score_of_interest)}

结果:过程默认值错误(x,预测器,绘图=真,…(:未提供有效数据。roc_plot(mtcars,vs(

这里有一个按需工作的解决方案(即让用户为score_of_interest指定不同的值(:

library(pROC)
data(mtcars)
plot.roc(mtcars$vs, mtcars$mpg) # --> makes correct graph
# expects `score_of_interest` to be a string!!!
roc_plot <- function(dataframe_of_interest, score_of_interest) {
plot.roc(dataframe_of_interest$vs, dataframe_of_interest[, score_of_interest])
}
roc_plot(mtcars, 'mpg')
roc_plot(mtcars, 'cyl')

请注意,您的错误不是由错误的列名引起的,而是由data.frame类的错误使用引起的。注意一个更简单的函数会发生什么:

foo <- function(x, col_name) {
head(x$col_name)
}
foo(mtcars, mpg)
## NULL

这将返回NULL。因此,在您最初的函数中,当您尝试为plot.roc提供dataframe_of_interest$score_of_interest时,实际上是在为plot.roc提供NULL

当列名存储在对象中时,有几种方法可以通过列名从data.frame中提取列(这就是在函数中将其作为参数传递时所做的操作(。也许最简单的方法是记住data.frame就像一个2D数组类型的对象,因此我们可以使用熟悉的object[i, j]语法,但我们要求所有行,并按名称指定列,例如mtcars[, 'mpg']。如果我们将字符串'mpg'分配给一个对象,这仍然有效:

x <- 'mpg'
mtcars[, x]

这就是我提出解决方案的方式。更进一步,不难想象您将如何同时提供score_of_interestthreshold_of_interest:

roc_plot2 <- function(dataframe_of_interest, threshold_of_interest, score_of_interest) {
plot.roc(dataframe_of_interest[, threshold_of_interest], 
dataframe_of_interest[, score_of_interest])
}
roc_plot2(mtcars, 'vs', 'mpg')

最新更新