Evaluate call that contains another call (call within call)

后端 未结 5 1659
-上瘾入骨i
-上瘾入骨i 2021-02-19 06:41

I have encountered a snippet of code where call contains another call. For example:

a <- 1
b <- 2
# First call
foo <- quote(a + a)
# Second call (call c         


        
5条回答
  •  迷失自我
    2021-02-19 07:45

    Here's something that (at least partially) works:

    evalception <- function (expr) {
        if (is.call(expr)) {
            for (i in seq_along(expr))
                expr[[i]] <- eval(evalception(expr[[i]]))
            eval(expr)
        }
        else if (is.symbol(expr)) {
            evalception(eval(expr))
        }
        else {
            expr
        }
    }
    

    It supports arbitrary nesting but will probably fail with objects of mode expression.

    > a <- 1
    > b <- 2
    > # First call
    > foo <- quote(a + a)
    > # Second call (call contains another call)
    > bar <- quote(foo ^ b)
    > baz <- quote(bar * (bar + foo))
    > sample <- quote(rnorm(baz, 0, sd=10))
    > evalception(quote(boxplot.stats(sample)))
    $stats
    [1] -23.717520  -8.710366   1.530292   7.354067  19.801701
    
    $n
    [1] 24
    
    $conf
    [1] -3.650747  6.711331
    
    $out
    numeric(0)
    

提交回复
热议问题