I was recently trying to compute a second derivative numerically in R, and I had some trouble finding a simple built-in function for the task. deriv takes expressions and finds symbolic derivatives. numericDeriv also uses takes expressions, and only finds the first derivative. I wrote a simpler derivative function that finds numerical derivatives with respect to a single variable.

In the following example, we find and plot the first four derivatives of $x^4/4$ on a grid over the interval $[-5, 5]$.

Be careful when youâ€™re taking higher derivatives; the round-off error can really add up. You may have to tune delta and sig to improve its performance.