## B.1 Operation

R commands to do derivatives of a defined function Taking derivatives in R involves using the expression, D, and eval functions. You wrap the function you want to take the derivative of in expression(), then use D, then eval as follows.

simple example

#define a function
f=expression(sqrt(x))

#take the first derivative
df.dx=D(f,'x')
df.dx
## 0.5 * x^-0.5
#take the second derivative
d2f.dx2=D(D(f,'x'),'x')
d2f.dx2
## 0.5 * (-0.5 * x^-1.5)

Evaluate
* The first argument passed to eval is the expression you want to evaluate * the second is a list containing the values of all quantities that are not defined elsewhere.

#evaluate the function at a given x
eval(f,list(x=3))
## [1] 1.732051
#evaluate the first derivative at a given x
eval(df.dx,list(x=3))
## [1] 0.2886751
#evaluate the second derivative at a given x
eval(d2f.dx2,list(x=3))
## [1] -0.04811252