使用 for 循环和 pROC 包在 R 中计算多条 ROC 曲线。在预测字段中使用什么变量?

Calculating multiple ROC curves in R using a for loop and pROC package. What variable to use in the predictor field?

我正在使用 pROC 包,我想使用 for 循环计算多个 ROC 曲线图。 我的变量是作为字符串包含在向量中的特定列名,我希望 pROC 按顺序读取该向量并使用字段 "predictor" 中似乎接受 text/characters 的字符串。 但是,我无法正确解析变量,因为出现错误:

'predictor' argument should be the name of the column, optionally quoted.

这是一个带有 SAH 数据集的示例代码:

ROCvector<- c("s100b","ndka")
for (i in seq_along(ROCvector)){
  a<-ROCvector[i]
pROC_obj <- roc(data=aSAH, outcome, as.character(a))

#code for output/print#

}

我尝试只调用 "a" 并使用函数 print() 或 get() 但没有任何结果。 当然,手动编写变量(带或不带引号)是可行的。 关于我应该在预测字段中使用的变量类型,我是否遗漏了什么?

roc可以接受公式,所以我们可以用paste0as.formula来创建一个。即

library(pROC)
ROCvector<- c("s100b","ndka")
for (i in seq_along(ROCvector)){
    a<-ROCvector[i]
    pROC_obj <- roc(as.formula(paste0("outcome~",a)), data=aSAH)
    print(pROC_obj)
    #code for output/print#

}

要获得原始调用,即没有 paste0,您可以稍后用于下游计算,请使用 evalbquote

pROC_obj <- eval(bquote(roc(.(as.formula(paste0("outcome~",a))), data=aSAH)))

通过将 data=aSAH 作为第一个参数传递,您将触发 non-standard evaluation (NSE) of arguments, dplyr-style. Therefore you cannot simply pass the column name in a variable. Note the inconsistency with outcome that you pass unquoted and looks like a variable (but isn't)? Fortunately, functions with NSE in dplyr come with an equivalent function with standard evaluation, whose name ends with _。 pROC 包遵循此约定。如果您使用列名进行编程,通常应该使用它们。

长话短说,您应该改用 roc_ 函数,它接受字符作为列名(不要忘记引用 "outcome"):

pROC_obj <- roc_(data=aSAH, "outcome", as.character(a))

您的代码的一个稍微更惯用的版本是:

for (predictor in ROCvector) {
    pROC_obj <- roc_(data=aSAH, "outcome", predictor)
}