【问题标题】:Managing argument input value usage inside an R function在 R 函数中管理参数输入值的使用
【发布时间】:2019-05-18 15:38:51
【问题描述】:

我的函数 foo 旨在使用以下参数之一计算名为 d 的变量:stf

例如,如果用户使用foo(n = 30:35, s = 1:2, t = 3:5, f = 7),我希望foo 首先使用t 计算d,然后是f,然后是s。因此,在输出中,我期望 6 ds(即,2 来自 t,1 来自 f,2 来自 s)。

我希望前 2 个ns 用于t,下一个n 用于f,剩下的ns 用于s。有没有办法以这种方式在函数内部管理ns?

foo <- function(n, s = NULL, t = NULL, f = NULL){

d1 <- if(!is.null(t)) t + n else NULL
d2 <- if(!is.null(f)) f^2 + n else NULL

m <- if(!is.null(s)) s/2 + n else NULL
r <- if(!is.null(m)) m + 1 else NULL

d3 <- if(!is.null(m)) m + r else NULL

data.frame(d = c(d1, d2, d3))
}

 # Example of use:
 foo(n = 30:35, s = 1:2, t = 3:5, f = 7)

【问题讨论】:

    标签: r function


    【解决方案1】:

    我们可以循环遍历't'、'f'、's'的元素,将(+)和'n'相加,得到list的输出

    foo <- function(n, s = NULL, t = NULL, f = NULL){
    
          dts <-  if(!is.null(t)) sapply(t, `+`, n) else NULL
          dfs <- if(!is.null(f)) sapply(f^2, `+`,  n) else NULL
    
          ms <- if(!is.null(s)) sapply(s/2, `+`,  n) else NULL
          rs <- if(!is.null(ms)) ms + 1 else NULL
    
          dss <- if(!is.null(ms)) ms + rs else NULL
    
          list(t_out =dts, f_out = dfs, s_out = dss)
          }
    
     # Example of use:
    foo(n = 30:35, s = 1:2, t = 3:5, f = 7)
    

    【讨论】:

    • 谢谢,我真正的函数不会用+我只是用了一个简单的例子。但我认为我无法实现我的想法。无论如何,非常感谢。
    • @rnorouzian 如果是复杂的函数,使用匿名函数调用sapply(t, function(x) yourfunction(x, n))
    • 阿伦,This很难实现吗?
    猜你喜欢
    • 2020-08-22
    • 2013-06-20
    • 1970-01-01
    • 1970-01-01
    • 2018-05-19
    • 2014-07-14
    • 1970-01-01
    • 2016-12-19
    • 1970-01-01
    相关资源
    最近更新 更多