r-使用pROC包发布计算AUC



我正在尝试使用一个函数,该函数调用R中的pROC包来计算曲线下的面积,以获得许多不同的结果。

# Function used to compute area under the curve
proc_auc <- function(outcome_var, predictor_var) {
pROC::auc(outcome_var, predictor_var)}

为了做到这一点,我打算在一个向量中引用结果名称(很像下面(。

# Create a vector of outcome names 
outcome <- c('outcome_1', 'outcome_2')

然而,我在定义要输入到此函数的变量时遇到了问题。当我这样做时,我生成错误:";roc.default中的错误(response,predictor,auc=TRUE,…(:"response"必须有两个级别;。然而,我不明白为什么,因为我认为我只有两个级别。。。

如果有人能帮助我,我会很高兴的!

以下是R.中虹膜数据集的可复制代码

library(pROC)
library(datasets)
library(dplyr)
# Use iris dataset to generate binary variables needed for function
df <- iris %>% dplyr::mutate(outcome_1 = as.numeric(ntile(Sepal.Length, 4)==4), 
outcome_2 = as.numeric(ntile(Petal.Length, 4)==4))%>%
dplyr::rename(predictor_1 = Petal.Width)
# Inspect binary outcome variables 
df %>% group_by(outcome_1) %>% summarise(n = n()) %>% mutate(Freq = n/sum(n))
df %>% group_by(outcome_2) %>% summarise(n = n()) %>% mutate(Freq = n/sum(n))
# Function used to compute area under the curve
proc_auc <- function(outcome_var, predictor_var) {
pROC::auc(outcome_var, predictor_var)}
# Create a vector of outcome names 
outcome <- c('outcome_1', 'outcome_2')
# Define variables to go into function
outcome_var <- df %>% dplyr::select(outcome[[1]])
predictor_var <- df %>% dplyr::select(predictor_1)

# Use function - first line works but not last line! 
proc_auc(df$outcome_1, df$predictor_1)
proc_auc(outcome_var, predictor_var)

outcome_varpredictor_var是具有一列的数据帧,这意味着它们不能直接用作auc函数中的参数。

只需指定列名,它就会起作用。

proc_auc(outcome_var$outcome_1, predictor_var$predictor_1)

您必须熟悉dplyr的非标准评估,这使得编程非常困难。特别是,您需要意识到传递变量名是一种间接,并且有一种特殊的语法。

如果您想继续使用管道/非标准求值,可以使用roc_函数,该函数遵循以前的命名约定,用于将变量名而不是实际列名作为输入的函数。

proc_auc2 <- function(data, outcome_var, predictor_var) {
pROC::auc(pROC::roc_(data, outcome_var, predictor_var))
}

此时,您可以将实际的列名传递给这个新函数:

proc_auc2(df, outcome[[1]], "predictor_1")
# or equivalently:
df %>% proc_auc2(outcome[[1]], "predictor_1")

话虽如此,对于大多数用例,您可能希望遵循@druskacik的答案并使用标准的R评估。

最新更新