ChuckP ChuckP - 2 months ago 6
R Question

Convenient way to find the i'th derivative of a function in r?

Is there a convenient way to find the i'th derivative of a (normal density) function in r?

Answer

Yes, there is. See help("D").

DD <- function(expr, name, order = 1) {
  if(order < 1) stop("'order' must be >= 1")
  if(order == 1) D(expr, name)
  else DD(D(expr, name), name, order - 1)
}

ddnorm <- function(x) eval(DD(expression(dnorm(x)), "x", order = 1))
dddnorm <- function(x) eval(DD(expression(dnorm(x)), "x", order = 2))

curve(dnorm(x), -2, 2, ylim = c(-0.4, 0.4))
curve(ddnorm(x), -2, 2, add = TRUE, col = "dark red")
curve(dddnorm(x), -2, 2, add = TRUE, col = "dark blue")
lines(seq(-2, 2, length.out = 100),
      c(attr(ddnorm(seq(-2, 2, length.out = 100)), "gradient")),
      col = "red")
legend(x = "topleft", legend = c("dnorm", "first derivative", "second derivative"),
       col = c("black", "dark red", "dark blue"),
       lty = 1)

resulting plot

Comments