【问题标题】:pass function argument down to other function with do.call使用 do.call 将函数参数传递给其他函数
【发布时间】:2013-10-20 17:39:30
【问题描述】:

我想将对象met 向下传递给函数sf,但得到对象未找到错误。我认为这可能与顶层函数调用的环境有关,它没有传递给子函数:

f <- function(fname,x,met=c('sum','subs')){

  .env <- environment() ## identify the environment
  do.call(fname,list(x,met),envir=.env)

}

sf <- function(x,...){

  if (met== 'sum') x + 100 else x - 100

}

f('sf',1:10,met='sum')

【问题讨论】:

  • f('sf',1:10,met='sum') 在我的机器上给出[1] 101 102 103 104 105 106 107 108 109 110 并且没有错误消息。但是,对于met='subs',结果是一样的。
  • @PhillipD 谢谢,我确实得到了错误,但无论如何 G. Grothendieck 找到了它的来源。

标签: r environment do.call


【解决方案1】:

如果met 没有作为sf 的参数显式传递,则不能在sf 的正文中通过名称引用met,所以试试这个:

sf <- function(x, met, ...) {
  if (met == 'sum') x + 100 else x - 100
}

如果我们假设met... 在对sf 的调用中的第一个组件(就像问题示例中的情况一样),那么这也可以:

sf <- function(x, ...) {
  met <- list(...)[[1]]
  if (met == 'sum') x + 100 else x - 100
}

这个更简洁的替代方案也有效:

sf <- function(x, ...) {
  met <- ...[[1]]
  if (met == 'sum') x + 100 else x - 100
}

这个替代方案更简洁:

sf <- function(x, ...) {
  met <- ..1
  if (met == 'sum') x + 100 else x - 100
}

我们在这里并不真正需要 env 参数到 do.call

更新:更正。

【讨论】:

  • 我想避免明确传递参数,第二个选项就像一个魅力,非常感谢!第三个选项中的..1 是做什么的?
  • ..1... 的第一个组件。见?..1
猜你喜欢
  • 2014-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-02
  • 2011-11-01
  • 1970-01-01
  • 2013-10-05
相关资源
最近更新 更多