[SOLVED] transfer character in function to the function in r

Issue

I have such a problem, I want to define the grad function as an input of the function. Please see the example below.

f<-function(grad="2*m-4"){
y=grad
return(y)
}
f(3)=2

Solution

I’m usually not a fan of using eval(parse(text=..)), but it does do this with a character string:

f <- function(m, grad="2*m-4"){
  eval(parse(text = grad))
}
f(3)
# [1] 2

The two take-aways:

  • if your grad formula requires variables, you should make them arguments of your function; and

  • parse(text=..) parse the string as if the user typed it in to R’s interpreter, and it returns an expression:

    parse(text="2*m - 4")
    # expression(2*m - 4)
    

    This expression can then be evaluated with eval.

Answered By – r2evans

Answer Checked By – Marie Seifert (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *