Search code examples
revalradix

eval parse character into function call r


I have an externally specified object with class character:

X = "c(Arg1 = 'First', Arg2 = 'Second', Arg3 = 'Third')"

that I want to directly plug into a function in R simply as foo(X)

The following is an example of what I want done:

Inputs <- eval(parse(text = X))

Msg_Foo <- function(Arg1, Arg2, Arg3) {
    message(paste(Arg1, Arg2, Arg3, sep = "\n"))
 }

Msg_Foo(
    Arg1 = Inputs["Arg1"], 
    Arg2 = Inputs["Arg2"],
    Arg3 = Inputs["Arg3"]
    )

But ideally I want a solution that simply requires:

Msg_Foo(Inputs)

This is important as I want to specify an ellipse (...) in the function, so that arguments from X is directly passed through to function without explicit specification as in the example above.


Solution

  • It's generally not a good idea to eval/parse strings in R unless you are 100% sure they are safe.

    But you can dynamically pass arguments to functions with do.call(). For example

    # X = "c(Arg1 = 'First', Arg2 = 'Second', Arg3 = 'Third')"
    # Inputs <- eval(parse(text = X))
    
    Msg_Foo <- function(x) {
      message(do.call("paste", c(as.list(x), sep="\n")))
    }    
    Msg_Foo(Inputs)
    

    Your inputs are a named character vector. We need to turn that into a named list to use with do.call and then can pass those to the paste function. Then we just pass the result to the message() function as normal