Nanitous
Nanitous

Reputation: 143

how to pass an variable of an expression to curve() as its equation?

I've the following code:

e <- expression(x^2+3*x-3)

I want to draw the plot of the first derivative using R's symbolic derivate function D:

curve(D(e), from=0, to=10)

But then I get the following error:

Error in curve(expression(e), xname = "x", from = 0, to = 3000) : 
     'expr' must be a function, or a call or an expression containing 'x'

I tried to wrap D(e) in a call to eval(), but to no avail.

Trying a bit more:

substitute(expression(x^2+3*x-3), list(x=3))

results, as expected, in:

 expression(3^2+3*3-3)

But:

 substitute(e, list(x=3))

results in:

 e

What is happening? How can I get this working?

Upvotes: 10

Views: 1206

Answers (2)

Karl Forner
Karl Forner

Reputation: 4414

functions are simpler to manipulate and test:

e <- expression(x^2+3*x-3)
de <- D(e, 'x')
fde <- function(x) eval(de)

curve(fde, from=0, to=10)

Upvotes: 5

Ben Bolker
Ben Bolker

Reputation: 226087

It's a little clunky, but

eval(substitute(curve(y),list(y=D(e,"x"))))

seems to work. So does

do.call(curve,list(D(e,"x")))

Upvotes: 7

Related Questions