Search code examples
rfunctionsyntaxnse

Correct syntax for using special function call in call


I'm interested in making use of a special call within call/eval as in the code:

eval(call("mean", c(2,3)))

which will correctly produce result 2.5. Now, I would like to use the same syntax with a special call.

Example: +

  1. Call:

    eval(call("`+`", c(2,3)))
    

    produces error:

    Error in eval(expr, envir, enclos) : could not find function "+"

  2. Similarly with the call,

    eval(call("+", c(2,3)))
    

    does not produce desired results:

    [1] 2 3
    

Desired result should simply return vector of length 1 with single value 5 as obtained via 2 + 3 call.


Solution

  • eval(call("+", c(2,3))) is working perfectly fine. You are calling unary plus with a vector, which returns the identical vector.

    If you want to use binary plus, you need to supply two arguments:

    eval(call("+", 2, 3))
    #[1] 5
    

    But do.call should be preferable in production code:

    do.call("+", list(2, 3))
    #[1] 5