【问题标题】:Passing optional arguments inside a wrapper function to a sub-function将包装函数内的可选参数传递给子函数
【发布时间】:2013-08-19 21:20:56
【问题描述】:

我有一个包装函数,我需要将可选参数传递给指定的子函数。但是有很多不同的可能子功能,我无法预先指定它们。 作为参考,子功能存在于环境等...... 考虑:

funInFun<- function (x, method, ...) {    

  method.out <- function(this.x, FUN, ...) {
    FUN <- match.fun(FUN)
    c <- FUN(this.x, ...)
    return(c)
  }

  d <- method.out(x, method)
  return(d)
}

data<-seq(1,10)
funInFun(data, mean) #  Works

data<-c(NA,seq(1,10))
funInFun(data, mean, na.rm=TRUE) # Should remove the NA

funInFun(c(seq(1,10)), quantile, probs=c(.3, .6))  # Shoudl respect the probs option. 

【问题讨论】:

    标签: r function


    【解决方案1】:

    您需要将... 传递给method.out。然后它工作正常:

    funInFun<- function (x, method, ...) {    
    
      method.out <- function(this.x, FUN, ...) {
        FUN <- match.fun(FUN)
        c <- FUN(this.x, ...)
        return(c)
      }
    
      d <- method.out(x, method, ...)  # <<--- PASS `...` HERE
      return(d)
    }
    
    data<-seq(1,10)
    funInFun(data, mean) #  Works
    # [1] 5.5    
    
    data<-c(NA,seq(1,10))
    funInFun(data, mean, na.rm=TRUE) # Should remove the NA
    # [1] 5.5
    
    funInFun(c(seq(1,10)), quantile, probs=c(.3, .6)) 
    # 30% 60% 
    # 3.7 6.4
    

    【讨论】:

      【解决方案2】:

      除了Thomas' answer OP 的问题之外,您可能必须转发一个可选参数,该参数是包装函数的显式参数。

      在这种情况下,您可以使用missing 构造一个缺少参数的调用,而不是在包装器定义中重复包装函数的默认值。

      f <- function(s = "world!") cat("Hello", s)
      f()
      # Hello world!
      g <-  function(s = NULL) eval(substitute(
        f(s = sub_me), 
        list(sub_me = if(missing(s)) quote(expr =) else s)))
      g()
      # Hello world!
      g("you!")
      # Hello you!
      

      【讨论】:

      • 虽然这不能回答 OPs 问题正文中所述的问题,但它提供了我在 google 上阅读问题标题时正在寻找的答案。
      猜你喜欢
      • 2013-10-04
      • 2020-07-29
      • 2012-06-19
      • 2019-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-17
      相关资源
      最近更新 更多