Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluate character string without quotation marks as expression

Tags:

r

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.

like image 465
Manuel Weinkauf Avatar asked Jun 08 '26 00:06

Manuel Weinkauf


1 Answers

You can use parse to create the expression:

D(parse(text=Function), "x")
2 * x
like image 134
agstudy Avatar answered Jun 10 '26 18:06

agstudy