[R] Computing High Order Derivatives (Numerically)

Gildas Mazo gildas.mazo at inria.fr
Fri Mar 23 00:35:57 CET 2012


Dear R users,

Let f be a function over d variables x1,..,xd. I want to compute the k^th-order derivative with respect to x1,..,xk (k<=d). I have a by hand solution (see below) using an iterating code using D. However, I expect d to be high and f to be complicated. Then I want a vector x to be the input, instead of x1,..,xd. How to avoid the x1 <- x[1]; x2 <- x[2], etc steps in the code below? Moreover, D uses symbolic differentation and then eval evaluates the output to get a numerical result. But is there a way to compute the desired derivatives numerically directly (without using symbolic calculus at all)? Finally, what is the most efficient and fast way to get a numerical result for such derivatives?

Thank you very much in advance,
Gildas

### Code ###
### dif takes a function f, an order k, and a vector x as input. f must be a function of x1,..,xd with d >= k. The correspondance is done between xi and x[i]. The expression for f must be at the last row of the body function.
dif <- function(f,k,x){
  o <- list()
  n <- length(body(f))
  o[[1]] <- body(f)[[n]]
  for (i in 1:k){
    xi <- paste("x",i,sep="")
    o[[i+1]] <- D(o[[i]],name=xi)
  }
  x1 <- x[1]
  x2 <- x[2]
  x3 <- x[3]
  eval(o[[k+1]])
}

### Examples ###
## function to differentiate
f <- function(x){
  x1 <- x[1]
  x2 <- x[2]
  x3 <- x[3]
  0.5*x1*x2*x3^2
}
## derivative w.r.t. x1, x2 and x3 at the point (1,2,3).
dif(f,3,c(1,2,3))

### My Questions ###
## how to avoid to write by hand xi <- x[i] ??
## is there a way in R to compute such derivatives without using symbolic calculation but numerical compuation instead.



More information about the R-help mailing list