【问题标题】:How to provide dynamic number of arguments to a function inside a function in R?如何在R中的函数内为函数提供动态数量的参数?
【发布时间】:2021-09-22 22:24:20
【问题描述】:

我有一个函数f1 执行一些任务。假设它执行以下任务:

f1 = function(a=1,b=1,c=2){
  res = (a+b)*c
  return(res)
}

现在,这个函数是通过另一个函数调用的,f2。此函数可以采用动态数量的参数,创建所有可能的组合并将值提供给函数f1,如下所示:

f2 = function(...){
  arglist = list(...)
  df = expand.grid(arglist) # Create all possible combinations of the given argument list.
  out = apply(df,1,function(x) f1(x))
  res = unlist(out)
  return(res)
}

现在,用户可以在f2 中为f1 的任意数量的参数提供值,例如:

f2(a=10)
# Output: 22

但是,如果我尝试任何其他方案,我都不会得到理想的结果:

f2(c=10)
# f2 Output: 22
# Target Output: 20

f2(a=5, c=c(5,10))
# f2 Output: 
12 12
12 22
# Target Output: 30 60

有关如何通过f2 将此类动态参数传递给f1 的任何建议?我看过其他问题,例如 1 和 2,但我认为它们没有解决这个问题。

【问题讨论】:

    标签: r function variables dynamic arguments


    【解决方案1】:

    如果将apply 更改为do.call,它将按预期工作。请注意,apply 和 MARGIN = 2 分别循环遍历 'df' 的列,而 'f1' 需要所有可用列的值(或者使用默认值)来计算 ((a + b) * c)

    f2 <- function(...){
      arglist = list(...)
      df = expand.grid(arglist) 
      do.call(f1, df)
    }
    

    还有f1

    f1 <- function(a=1,b=1,c=2){
      (a+b)*c
     
    }
    

    -测试

    > f2(a = 10)
    [1] 22
    > f2(c = 10)
    [1] 20
    > f2(a = 5, c= c(5, 10))
    [1] 30 60
    

    【讨论】:

      猜你喜欢
      • 2018-05-15
      • 1970-01-01
      • 1970-01-01
      • 2018-11-25
      • 2014-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多