Search code examples
rderivative

Calculate Derivative of Function at a Point in R


Reading through this documentation in R, I don't understand how to take a derivative of the function at a specific point.

They do it here in C (with gsl_deriv_central/forward/backward), but I was wondering if there is an equivalent in R?


Solution

  • Just install the package numDeriv and use the grad function. Here are a few simple examples that are easy to check.

    library(numDeriv)
    
    grad(sin, 1:3)
    [1]  0.5403023 -0.4161468 -0.9899925
    cos(1:3)
    [1]  0.5403023 -0.4161468 -0.9899925
    
    
    f = function(x) x^2 + 2*x +3
    grad(f, 1:3)
    [1] 4 6 8
    2*(1:3) + 2
    [1] 4 6 8