【问题标题】:How to retrieve contents of ... as list of calls?如何检索...的内容作为呼叫列表?
【发布时间】:2014-04-24 12:58:13
【问题描述】:

如果我想查看传递给函数的表达式,我可以使用substitute 检索它。

f <- function(x)
{
  substitute(x)  
}

f(sin(pi))
## sin(pi)

f返回一个call类的对象。substitute通常与deparse结合起来变成一个字符向量,但我这里不关心。)

我想用... 中的参数重复这一点。此尝试仅返回第一个参数:

g <- function(...)
{
  substitute(...)
}

g(sin(pi), cos(pi / 2))
## sin(pi)

此尝试引发错误:

h <- function(...)
{
  lapply(..., subsitute)
}

h(sin(pi), cos(pi / 2))
## Error in match.fun(FUN) :
##   'cos(pi/2)' is not a function, character or symbol

此尝试引发不同的错误:

i <- function(...)
{
  lapply(list(...), substitute)
}

i(sin(pi), cos(pi / 2))

## Error in lapply(list(...), substitute) : 
##   '...' used in an incorrect context

如何检索我传递给... 的表达式?

【问题讨论】:

    标签: r parsing arguments expression substitution


    【解决方案1】:

    如果你想保留类调用的对象:

    i <- function(...)
    {
      l <- match.call()
      l <- as.list(l)
      l <- l[-1]
      l
    }
    
    i <- function(...)
    {
      l <- match.call()
      l[[1]] <- as.name("expression")
      l
    }
    i(sin(pi), cos(pi/2))
    

    或者也许你只需要 match.call 取决于你想做什么。 hth

    【讨论】:

    • 啊,是的。我忘了match.callas.list(match.call())[-1] 是我想要的。
    • 我更喜欢这个版本:)
    【解决方案2】:

    试试这个:

    substitute_multi <- function(...) {
       f <- function(e1, ...) {
          if (missing(e1)) return(NULL)
          else return(list(substitute(e1), substitute_multi(...)))
       }
       unlist(f(...))
    }
    

    举个例子:

    substitute_multi(x, g(y), 1+2+3)
    ## [[1]]
    ## x
    ## 
    ## [[2]]
    ## g(y)
    ## 
    ## [[3]]
    ## 1 + 2 + 3
    

    您也可以在结果上调用as.expression 以获取expression 对象。

    恕我直言,这个解决方案不像其他解决方案那样优雅,但提供了一些关于 ... 如何处理函数参数的见解。 :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多