[R] Derivative of a function

Martin Maechler maechler at stat.math.ethz.ch
Tue Jul 5 15:37:14 CEST 2005

>>>>> "Gabor" == Gabor Grothendieck <ggrothendieck at gmail.com>
>>>>>     on Tue, 5 Jul 2005 09:14:20 -0400 writes:

    Gabor> On 7/4/05, Gabriel Rodrigues Alves Margarido
    Gabor> <gramarga at carpa.ciagri.usp.br> wrote:
    >> Suppose I have a simple function that returns a matrix, such as:
    >> test <- function(x){ return(matrix(c(x,x^2,x^3,x^4),2,2)) }
    >> so that test returns:
    >> [ x      x^3 ]
    >> [ x^2    x^4 ]
    >> Is it possible for me to get the derivative of an expression such as:
    >> c(1,0) %*% test() %*% c(0,1)
    >> The vectors are used just to "index" the matrix.
    >> I don't want a value, but the expression to work with (in that case,
    >> the expected expression would be 3*x^2)...
    >> Tried functions D and deriv in many ways, but no success.
    >> I will be grateful if anyone can help.

    Gabor> Note sure if this is good enough but in the following you can
    Gabor> replace 1,2 in the third line with other indices to extract out any
    Gabor> matrix component and differentiate it.  e is a list that contains the
    Gabor> 4 expressions and idx[i,j] gives the index in e that contains
    Gabor> the i,j-th expression:

    Gabor> e <- lapply(1:4, function(i) bquote(x^.(i)))
    Gabor> idx <- matrix(1:4, 2)
    Gabor> e12 <- e[idx[1,2]][[1]]
    Gabor> D(e12, "x")

neat, Gabor!

The following may also be useful {after the initial "e <- lapply(....)"}:

  De <- lapply(e, D, "x")
  dim(De) <- c(2,2)

  > De[[1,2]]
  3 * x^2
  > De[[2,2]]
  4 * x^3

Martin Maechler, ETH Zurich

More information about the R-help mailing list