簡體   English   中英

有條件地將參數傳遞給 R 函數

[英]Passing arguments conditionally to R functions

我有一個現有的函數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傳遞給我的函數,但arg2target == 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)

您可以制作一個包裝函數,將正確數量的參數分派給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"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM