I would like to use the D() function of R within a function, but I have trouble to get them evaluated, because D() only accepts the first argument as expression without quotation marks. Example:
> D(expression(x^2), "x")
2 * x
This works as it is supposed to. However, when I want to evaluate a function stored in a character vector, as would be the case for my purpose:
> Function<-"x^2"
> D(as.expression(Function), "x")
NA
Because as.expression(Function) returns expression("x^2") instead of expression(x^2)
So the question is: How do I either get rid of the quotation marks when using the content of character vector variable as as.expression() argument, or how do I otherwise transform the content of variable into the argument of expression() without the quotation marks.
Note: while print(Function, quote=FALSE) would produce x^2 (i.e. without quotation marks), D(as.expression(print(Function, quote=FALSE)), "x") does not work either.
You can use parse to create the expression:
D(parse(text=Function), "x")
2 * x
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With