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
CodePudding user response:
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
gradformula requires variables, you should make them arguments of yourfunction; andparse(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.
