函数参数;不带引号传递变量名

5
这个问题与这个问题类似:将data.frame列名传递给函数 我有一个函数:
optimal_cutpoint <- function(data, ..., choice){
  selection <- dplyr::select(data, ...)
  choice <- data[[choice]]
  # do something with those two objects
}

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

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")

现在来谈我的问题。使用...,我可以不用引号编写变量名称。是否有可能我可以不用引号编写 "VOTE"?我希望在函数中保持一致而不用引号。

如果我使用dplyr::select,它会搜索choice而不是vote。

dplyr::select(data,choice)
2个回答

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

3

这正是 quosure 的用途,详见此处。此外还提到了 pull 函数,它基本上相当于 dplyr 中的 [[

optimal_cutpoint <- function(data, ..., choice){
  choice_quo = enquo(choice)
  selection <- dplyr::select(data, ...)
  choice <-dplyr::pull(data, !!choice_quo)
  # do something with those two objects
}

我很惊讶在...中不带引号的参数可以自动工作,我以前从未尝试过。 编辑 关于quoenquo的额外澄清,因为我在原始答案中犯了这个错误。如果您直接使用未加引号的值,请使用quo,如果您要将未加引号的参数值解释为函数,则使用enquo。比较一下。
data(iris)
myvar = quo(Species)
select(iris, !!myvar)

为了

myfun = function(d, myvar) {
  quovar = enquo(myvar)
  select(iris, !!quovar)
}
myfun(iris, Species)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接