【问题标题】:How to pass down a missing argument in R?如何传递 R 中缺少的参数?
【发布时间】:2021-09-07 13:42:19
【问题描述】:

我有一个函数在内部调用另一个可能缺少参数的函数。如果我没有为高级函数中的参数定义默认的NULL 值,则丢失的参数将正确传递。但是,在函数文档中,我想通过为其分配默认的NULL 值来明确表明该参数是可选的。

在下面的 MWE 中,我怎样才能让 high.foo2() 工作起来更像 high.foo1()

low.foo <-  function(y = NULL) if(missing(y)) cat ('y is missing') else print(y)

high.foo1 <-  function(y) low.foo(y = y)
high.foo1()
# > y is missing

high.foo2 <-  function(y = NULL) low.foo(y = y)
high.foo2()
# > NULL

PD1。不是R how to pass a (potentially) missing argument?的重复项

【问题讨论】:

    标签: r function arguments parameter-passing


    【解决方案1】:

    捕获参数并检查它是否为"NULL"的选项

    high.foo2 <-  function(y = NULL) {
      if(deparse(substitute(y)) == "NULL") low.foo() else low.foo(y = y)
    
    }
    

    -测试

    high.foo2()
    y is missing
    

    或者可以使用is.null

    high.foo2 <-  function(y = NULL) {
      if(is.null(substitute(y))) low.foo() else low.foo(y = y)
    
    }
    high.foo2()
    y is missing
    

    【讨论】:

    • 您的回答确实很有帮助,谢谢。但是,我有几个论点分享这种情况,并认为以这种方式处理这可能会有点困难......您对如何概括您的解决方案有任何想法吗? D:
    • @Crparedes 如果你有多个参数,那么使用as.list(match.call()) 然后检查其中哪个是NULL
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-12
    • 1970-01-01
    • 1970-01-01
    • 2021-07-24
    • 2014-12-28
    相关资源
    最近更新 更多