Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

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?

like image 304
Nanitous Avatar asked Oct 17 '13 14:10

Nanitous


2 Answers

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")))
like image 89
Ben Bolker Avatar answered Nov 11 '22 05:11

Ben Bolker


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)
like image 22
Karl Forner Avatar answered Nov 11 '22 06:11

Karl Forner