我正在尝试编写一个函数来根据必须预测结果的不同评分系统绘制ROC曲线。
我有一个数据框data_all,其列为“ score_1”和“ Threshold.2000”。我通过以下方法生成了ROC曲线:
plot.roc(data_all$Threshold.2000, data_all$score_1)
我的目标是为许多不同的结果(例如Threshold.1000)和分数(分数score_1,score_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)}
结果:roc.default(x,预测变量,plot = TRUE,...)中的错误:未提供有效数据。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
当该名称存储在对象中时,有几种方法可以从列名中提取列(当您将其作为函数的参数传递时,这就是您要做的事情)。也许最简单的方法是记住adata.frame
类似于2D数组类型的对象,因此我们可以使用熟悉的object[i, j]
语法,但是我们要求所有行,并按名称指定列,例如mtcars[, 'mpg']
。如果我们将字符串分配给'mpg'
对象,这仍然有效:
x <- 'mpg'
mtcars[, x]
这就是我提出解决方案的方式。再进一步,不难想象您将如何同时提供ascore_of_interest
和a threshold_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')
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句