function-expression R problem when using curve()

When plot using curve() in R I give a function as an argument.
E.g.

f=function(x) x^2
curve(f,2,3)

I get the curve plotted.

But I have to work with the derivative function D(), which you have to give an expression as argument and I can't get my curve plotted.

This is my code:

#To get the derivative
f1 = expression((x)^2)
d1=D(f1,"x")

#To plot the curve
f1=function(x) eval(f1,"x")
curve(f1,2,3)

And the error is:

Error in eval(f1, "x") : invalid 'envir' argument of type 'character' 

How can I fixed? I've tried to plot directly the expression and no result. I can fix the problem if I were able to convert the function to expression, but no clue either.

Thanks in advance, Alberto.

Upvotes: 2

Views: 210

Answers (1)

Krzysztof Nowicki
Krzysztof Nowicki

Reputation: 100

I think you've mistyped because you want to evaluate d1 and NOT f1

#To get the derivative
f1 = expression((x)^2)
d1=D(f1,"x")

#To plot the curve
f=function(x) eval(f1)
curve(f,2,3)

The code above works for me.

Plot

Upvotes: 2

Related Questions