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 and 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 and .
Note that in the case of scalar functions, inserting a vector into the x
option also properly calculates the gradient.