Alex Alex Alex Alex - 6 days ago 7
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

f<-function(x){x^2}


After that I want to have a derivative function
g
, 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
x^2
, but there is no way to differentiate
f<-function(x){x^2}
.

I have tried to do something like this:

f<-function(x){x^2}
g<-Deriv(f,"x")


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
#Result:
"2*x"


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

Answer

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
Comments