How to Calculate the Derivative in R
Overview
To compute derivatives in R, one can use the grad()
function from the numDeriv
package.
Code
For example, the derivatives of $f(x) = x^2 + 4x + 1$ and $g(x) = e^{-x}$ can be computed as follows.
install.packages("numDeriv")
library(numDeriv)
f<-function(x) {x^2 + 4*x + 1}
g<-function(x) {exp(-x)}
grad(f,2)
grad(g,0)
Upon actual computation, it is confirmed that it is $f ' (2) = 2 \cdot 2 + 4 = 8$ and $g ' (0) = - e^{0} = -1$.
Note that in the case of scalar functions, inserting a vector into the x
option also properly calculates the gradient.