【问题标题】:Code snippet in R needed to illustrate + operatorR 中的代码片段需要说明 + 运算符
【发布时间】:2020-11-07 14:57:51
【问题描述】:

在 R 中有一句老话“一切都是函数”,甚至像 + 这样的运算符也是如此。我在某处读到他们发布了一些代码,向您展示了当您添加 A + B 时基本上在幕后工作的函数,例如 Y

【问题讨论】:

    标签: r function operators


    【解决方案1】:

    您还可以使用 lobstr 之类的 pacakge 来获取 R 代码的抽象语法树。例如

    lobstr::ast(3+9)
    # o-`+` 
    # +-3 
    # \-9 
    

    这里显示表达式 3+9 是对 + 的调用,参数为 3 和 9。您可以执行更复杂的表达式,例如

    lobstr::ast(5*3-6/2)
    # o-`-` 
    # +-o-`*` 
    # | +-5 
    # | \-3 
    # \-o-`/` 
    #   +-6 
    #   \-2 
    

    【讨论】:

      【解决方案2】:

      有几种方法可以显示这一点。最直接的是将+ 作为函数调用:

      `+`(1, 2)
      #> [1] 3
      

      或者,您可以捕获像A + B 这样的表达式,并表明它实际上是对+ 的调用:

      f <- function(x) {
        x <- as.list(match.call())[[2]]
        cat("You have input a", class(x), "to function", as.list(x)[[1]], "with arguments", 
            sapply(as.list(x)[-1], as.character))
      }
      
      f(A + B)
      #> You have input a call to function + with arguments A B
      
      f(A / B)
      #> You have input a call to function / with arguments A B
      
      f(A > B)
      #> You have input a call to function > with arguments A B
      

      【讨论】:

        猜你喜欢
        • 2017-12-24
        • 2012-08-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多