Alex Alex Alex Alex - 1 month ago 13
R Question

Derivative of f, such that f<-function(x){x^2} (or similar) without yacas

I need to find derivative of function defined like


After that I want to have a derivative function
, such that I would be able to get something like:

g(5) # entered
10 # answer

without Yacas or similar heavy software. I find it surprising that R can find the derivative of
, but there is no way to differentiate

I have tried to do something like this:


I got an error:

Error in list2env(list(), NULL, <environment>) :
names(x) must be a character vector of the same length as x

I have also tried this:

> f1<-'x^2'
> g<-Deriv(f1,"x")
> g

Can I transform my function f to a one like f1 and reverse the process?
Is there another way?


You could define your function as an expression:

f <- expression(x^2)

Such an expression can be treated like a function by using eval():

#> eval(f,list(x=2))
#[1] 4

In this case, the advantage of an expression instead of a function is that the former allows for the use of symbolic calculus to obtain the first derivative:

g <- D(f,"x")
#> g
#2 * x

To evaluate this expression of the first derivative (more precisely its class is a call), you can use the same syntax as was done before for f:

#> eval(g,list(x=5))
#[1] 10