【问题标题】:Select Output in User Defined Function in R在 R 中的用户定义函数中选择输出
【发布时间】:2014-09-28 19:18:51
【问题描述】:

我编写了一个函数,它产生 2 个矩阵作为输出,比如 A 和 B,并且我使用了list() 以便在我的输出中将它们分开。现在我想重新编写我的函数,以便显示的输出仅为矩阵 B,除非我在调用函数时指定它(但是,我的函数仍然需要计算两个矩阵。)基本上,我想 hide 除非我另有说明,否则输出中的矩阵 A。

我可以在 R 中做到这一点吗?

【问题讨论】:

    标签: r function output user-defined-functions


    【解决方案1】:

    是的。

    这是一个例子:

    myfun <- function(a, b, Bonly=TRUE) {
      # calculations
      result <- list(a, b)
      if (Bonly) return(result[2]) else return(result)
    }
    

    基本上,您在传递给函数的参数集中使用符号 x=DEFAULT 在函数中设置一个具有默认值的变量。无需为函数指定变量即可运行。如果变量具有默认值,则只返回 B,否则返回两者。

    > myfun(1,2)
    [[1]]
    [1] 2
    
    > myfun(1,2, FALSE)
    [[1]]
    [1] 1
    
    [[2]]
    [1] 2
    

    【讨论】:

      【解决方案2】:

      您可以使用默认值设置参数,表示矩阵 A 应该隐藏,除非用户指定它应该是结果的一部分

      myFunction <- function(<your arguments>, hideA = TRUE){
      
        #your computations
        ...
        output <- list(A = <matrix A>, B = <matrix B>)
      
        #your result
        if(hideA) output <- output$B #hide A
        return(output)
      }
      
      
      #calling the function
      myFunction(<your args>) #A will be hidden by default
      myFunction(<your args>, hideA = FALSE) #the list of matrix will be returned 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-09-26
        • 1970-01-01
        • 1970-01-01
        • 2010-10-09
        • 1970-01-01
        • 2022-09-23
        • 2010-11-20
        • 1970-01-01
        相关资源
        最近更新 更多