选择要在 R 中动态传递的参数
Selecting Which Argument to Pass Dynamically in R
我正在尝试将特定参数动态传递给函数,其中该函数对大多数或所有参数都具有默认值。
这是一个玩具示例:
library(data.table)
mydat <- data.table(evildeeds=rep(c("All","Lots","Some","None"),4),
capitalsins=rep(c("All", "Kinda","Not_really", "Virginal"),
each = 4),
hellprobability=seq(1, 0, length.out = 16))
hellraiser <- function(arg1 = "All", arg2= "All "){
mydat[(evildeeds %in% arg1) & (capitalsins %in% arg2), hellprobability]}
hellraiser()
hellraiser(arg1 = "Some")
whicharg = "arg1"
whichval = "Some"
#Could not get this to work:
hellraiser(eval(paste0(whicharg, '=', whichval)))
我希望有一种方法可以动态指定我正在调用的参数:换句话说,得到与 hellraiser(arg1="Some")
相同的结果,但同时选择是否发送 arg1 OR arg2 动态。目标是能够调用仅指定一个参数的函数,并动态指定它。
我设法通过
得到了结果
hellraiser(eval(parse(text=paste(whicharg, ' = \"', whichval, '\"', sep=''))))
您可以使用某种形式的do.call
,例如
do.call("hellraiser", setNames(list(whichval), whicharg))
但实际上这似乎是处理函数参数的一种糟糕方式。将您的参数视为您可以更轻松地操作的列表可能会更好。这是一个允许您选择参数名称被视为列名称的值的版本
hellraiser2 <- function(..., .dots=list()) {
dots <- c(.dots, list(...))
expr <- lapply(names(dots), function(x) bquote(.(as.name(x)) %in% .(dots[[x]])))
expr <- Reduce(function(a,b) bquote(.(a) & .(b)), expr)
eval(bquote(mydat[.(expr), hellprobability]))
}
hellraiser2(evildeeds="Some", capitalsins=c("Kinda","Not_really"))
hellraiser2(.dots=list(evildeeds="Some", capitalsins=c("Kinda","Not_really")))
...
和 .dots=
语法的使用是从 dplyr
标准评估函数中借用的。
我正在尝试将特定参数动态传递给函数,其中该函数对大多数或所有参数都具有默认值。
这是一个玩具示例:
library(data.table)
mydat <- data.table(evildeeds=rep(c("All","Lots","Some","None"),4),
capitalsins=rep(c("All", "Kinda","Not_really", "Virginal"),
each = 4),
hellprobability=seq(1, 0, length.out = 16))
hellraiser <- function(arg1 = "All", arg2= "All "){
mydat[(evildeeds %in% arg1) & (capitalsins %in% arg2), hellprobability]}
hellraiser()
hellraiser(arg1 = "Some")
whicharg = "arg1"
whichval = "Some"
#Could not get this to work:
hellraiser(eval(paste0(whicharg, '=', whichval)))
我希望有一种方法可以动态指定我正在调用的参数:换句话说,得到与 hellraiser(arg1="Some")
相同的结果,但同时选择是否发送 arg1 OR arg2 动态。目标是能够调用仅指定一个参数的函数,并动态指定它。
我设法通过
得到了结果hellraiser(eval(parse(text=paste(whicharg, ' = \"', whichval, '\"', sep=''))))
您可以使用某种形式的do.call
,例如
do.call("hellraiser", setNames(list(whichval), whicharg))
但实际上这似乎是处理函数参数的一种糟糕方式。将您的参数视为您可以更轻松地操作的列表可能会更好。这是一个允许您选择参数名称被视为列名称的值的版本
hellraiser2 <- function(..., .dots=list()) {
dots <- c(.dots, list(...))
expr <- lapply(names(dots), function(x) bquote(.(as.name(x)) %in% .(dots[[x]])))
expr <- Reduce(function(a,b) bquote(.(a) & .(b)), expr)
eval(bquote(mydat[.(expr), hellprobability]))
}
hellraiser2(evildeeds="Some", capitalsins=c("Kinda","Not_really"))
hellraiser2(.dots=list(evildeeds="Some", capitalsins=c("Kinda","Not_really")))
...
和 .dots=
语法的使用是从 dplyr
标准评估函数中借用的。