Search code examples
rterminalparameter-passing

Pass function as argument to Rscript through terminal


I want to pass a function as an argument of Rscript through Posit Terminal to evaluate a mathematical problem.

This is a reproducible example, where a script named imp.R contains:

#!/usr/bin/env Rscript
args = commandArgs(trailingOnly=TRUE)
x <- args[1]
f <- as.function(alist(x=, args[2]))
paste("The function is:", f(x))

With a Terminal call from Posit Page as:

/cloud/project$ Rscript imp.R "c(1,2,3)" sin(x^2)

I've got the error message: bash: syntax error near unexpected token ('`

But with: Rscript imp.R "c(1,2,3)" "sin(x^2)" it returns: "The function is: sin(x^2)".

Expected return: "The function is: [1] 0.8414710 -0.7568025 0.4121185"


Solution

  • This should work:

    #!/usr/bin/env Rscript
    args = commandArgs(trailingOnly=TRUE)
    x <- eval(parse(text=args[1]))
    f <- as.function(c(alist(x=),parse(text = "sin(x^2)")[[1]]))
    cat("The function is:")
    print(f(x))
    

    Then

    $ Rscript imp.R "c(1,2,3)" "sin(x^2)"
    The function is:[1]  0.8414710 -0.7568025  0.4121185
    

    However AVOID PARSING ARBITRARY INPUT since it is easy to inject malicious code that way. See https://stackoverflow.com/a/18391779/6912817