简体   繁体   中英

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?

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")))

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM