有条件地将参数传递给R函数

时间:2019-03-27 18:34:01

标签: r function

我有一个现有函数pass_thru(target,...),该函数根据其输入将参数传递给其他函数(例如a()b()c())。例如:

> target <- "a"
> arg1 <- "some input"
> arg2 <- "other input"
> pass_thru(target, arg1)
# This passes ellipses arguments to function `a()`

我想将arg2传递给我的函数,但仅当target == b传递给我的函数时,因为其他函数都不能接受arg2(即arg2 = NULL不起作用) 。此外,我无法更改pass_thru()

所需的效果如下,但不必重复pass_thru()

> if (target == "b") { pass_thru(target, arg1, arg2) }
  else { pass_thru(target, arg1) }

-
我正在运行的实际代码来自caret包。 verbose是在method = "glm"时中断功能的参数。

train(y ~ x, data,
      method = TARGET,
      trControl = ARG1,
      verbose = ARG2)

1 个答案:

答案 0 :(得分:0)

您可以创建包装函数,将正确数量的参数分配给pass_thru。这是一个虚拟的例子来演示

pass_thru = function(t, ...){
  a = function(arg1,arg2) paste(arg1,arg2)
  b = function(arg1) paste(arg1)
  get(t)(...)
}


pass_wrapper = function(target, ...){
  dots = list(...)
  if (target != 'a') dots[2] <- NULL
  do.call(pass_thru, c(target, dots))
}

pass_wrapper("a", arg1, arg2)
# "some input other input"
pass_wrapper("b", arg1, arg2)
# "some input"
相关问题