logo

How to Calculate the Derivative in R 📂R

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)=x2+4x+1f(x) = x^2 + 4x + 1 and g(x)=exg(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)

20190320\_151607.png

Upon actual computation, it is confirmed that it is f(2)=22+4=8f ' (2) = 2 \cdot 2 + 4 = 8 and g(0)=e0=1g ' (0) = - e^{0} = -1.

Note that in the case of scalar functions, inserting a vector into the x option also properly calculates the gradient.

See Also