【问题标题】:R: Having one function call other functions as well as passing arguments on to themR:让一个函数调用其他函数并将参数传递给它们
【发布时间】:2016-01-19 23:16:30
【问题描述】:

我有一系列这样的功能:

otherfunction<-function(x, y){
     if(option=="one"){
         z<-x+y+var
     }
     if(option=="two"){
         z<-x-y+2*var
     }
     return(z)
 }

然后是一个主函数,它定义了需要传递的参数,连同内部函数的输出,传递给其他内部函数函数,以及。

master <- function(x, y, option=c("one", "two"), variable=0.1){
    w <- otherfunction(x,y)
    #(or otherfunction(x,y, option, variable))     
    v <- otherfunction(w,y)
    return(v)
}

我似乎遇到了“找不到对象”或“未使用的参数”错误。

其他人如何处理从主函数调用的多个函数? 我是否需要将主函数中的参数值转换为对象?

这需要在全球环境中进行吗?

我需要在主函数中定义“其他函数”吗?

我需要使用某种“...”参数吗?

或者还有什么我没有得到的?

【问题讨论】:

    标签: r function arguments environment-variables


    【解决方案1】:

    您的otherfunction 无法从您的master 函数中查看option 值。函数在定义它们的环境中查找变量,而不是在调用它们的位置。这应该工作

    otherfunction<-function(x, y, option, var){
        if(option=="one"){
            z<-x+y+var
        }
        if(option=="two"){
            z<-x-y+2*var
        }
        return(z)
    }
    
    master <- function(x, y, option=c("one", "two"), variable=0.1){
        w <- otherfunction(x,y, option, variable)
        v <- otherfunction(w,y, option, variable)
        return(v)
    }
    master(2,2, "two")
    # [1] -1.6
    

    如果你想传递参数,你也可以用master做这样的事情

    master <- function(x, y, ...){
        w <- otherfunction(x,y, ...)
        v <- otherfunction(w,y, ...)
        return(v)
    }
    master(2,2, option="two", var=0.1)
    # [1] -1.6
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-04
      • 1970-01-01
      • 1970-01-01
      • 2016-02-01
      相关资源
      最近更新 更多