功能参数; 传递变量名称不带引号

Ben*_*gel 5 r dplyr

问题类似于这个问题:

将data.frame列名传递给函数

我有一个功能:

optimal_cutpoint <- function(data, ..., choice){
  selection <- dplyr::select(data, ...)
  choice <- data[[choice]]
  # do something with those two objects
}
Run Code Online (Sandbox Code Playgroud)

我将使用以下方式的函数:

choicedata <- data.frame(PTV.A = c(0, 10, 5, 4, 7, 1, 2, 0, 0, 10),
                     PTV.B = c(5, 0, 1, 10, 6, 7, 10, 9, 5, 0),
                     PTV.C = c(10, 5, 10, 5, 2, 8, 0, 5, 5, 0),
                     VOTE = c("C", "A", "C", "B", "B", "C", "B","B", "B", "A"))
optimal_cutpoint(choicedata, PTV.A:PTV.C, choice = "VOTE")
Run Code Online (Sandbox Code Playgroud)

现在问我的问题.有了...我可以写没有引号的变量名.我是否有可能在没有引号的情况下写出"投票"?我会优先写它没有引号在函数中保持一致.

如果我使用dplyr :: select它搜索选择而不是投票.

dplyr::select(data,choice)
Run Code Online (Sandbox Code Playgroud)

G. *_*eck 5

添加标记为##的行

optimal_cutpoint <- function(data, ..., choice){
  selection <- dplyr::select(data, ...)
  choice <- deparse(substitute(choice)) ##
  choice <- data[[choice]]
  # do something with those two objects
}

out <- optimal_cutpoint(choicedata, PTV.A:PTV.C, choice = VOTE)
out
## [1] C A C B B C B B B A
## Levels: A B C
Run Code Online (Sandbox Code Playgroud)