【问题标题】:Kind of arguments inheritance in nested functions in R?R中嵌套函数中的参数继承类型?
【发布时间】:2015-01-08 09:39:46
【问题描述】:

我正在用 R 编写一些函数,但遇到了一些问题。总而言之,在我正在编写的函数中,我调用了我开发的另一个函数。第二个函数与第一个函数共享一些参数,如何指定第二个函数的参数必须与第一个函数中的参数值相同?

first.fx=function(arg1,arg2,arg3,...){
  .
  .
  .
  second.fx=function(arg2,arg3,arg4,...){

  }
}

第二个.fx 与第一个 arg2 和 arg3 共享。如何将这些值继承到 second.fx?

【问题讨论】:

    标签: r


    【解决方案1】:

    只需分配值(来自对first.fx 的调用作为second.fx 定义中的默认参数:

    second.fx <- function(arg2=arg2,arg3=arg3,arg4,...){
    

    【讨论】:

      【解决方案2】:

      您不需要在second.fx 的定义中显式声明参数。通过词法作用域的魔法,这些变量将在second.fx 的封闭环境中找到,也就是first.fx 的环境。

      first.fx <- function(arg1, arg2, arg3, ...)
      {
           second.fx <- function(arg4)
           {
                # values of arg2/3 will be found from first.fx's environment
           }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-24
        • 1970-01-01
        • 1970-01-01
        • 2011-06-19
        • 1970-01-01
        相关资源
        最近更新 更多