[R] how to get higher derivatives with "deriv"

Marius Hofert m_hofert at web.de
Thu Jul 29 18:03:56 CEST 2010


Dear ExpeRts,

I have trouble implementing a function which computes the k-th derivative of a specified function f and returns it as a function. I tried to adapt what I found under ?deriv but could not get it to work. Here is how it should look like: 

## specify the function
f <- function (x,alpha) x^alpha

## higher derivatives
DD <- function(expr, variable, order = 1) {
   if(order < 1) stop("'order' must be >= 1")
   if(order == 1) deriv(expr, variable)
   else DD(deriv(expr, variable), variable, order - 1)
}

## compute the second derivative of f
f.prime.prime <- DD(f,"x",2)

## evaluate it at x=1 for alpha=0.5
f.prime.prime(1,0.5)


Many thanks,

Marius


More information about the R-help mailing list