Re: [R] Derivative of a function

From: Gabor Grothendieck <ggrothendieck_at_gmail.com>
Date: Tue 05 Jul 2005 - 23:35:01 EST

On 7/5/05, Gabor Grothendieck <ggrothendieck@gmail.com> wrote:
> On 7/4/05, Gabriel Rodrigues Alves Margarido
> <gramarga@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.
> >
>
> Note sure if this is good enough but in the following you can
> replace 1,2 in the third line with other indices to extract out any
> matrix component and differentiate it. e is a list that contains the
> 4 expressions and idx[i,j] gives the index in e that contains
> the i,j-th expression:
>

Here is an improvement that gets rid of idx:

> e <- lapply(1:4, function(i) bquote(x^.(i)))
> dim(e) <- c(2,2)
> D(e[1,2][[1]],"x")

3 * x^2



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Wed Jul 06 00:05:44 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:33:15 EST