[R] numericDeriv
Peter Dalgaard
p.dalgaard at biostat.ku.dk
Wed Nov 16 15:12:43 CET 2005
(Ted Harding) <Ted.Harding at nessie.mcc.ac.uk> writes:
> On 16-Nov-05 Florent Bresson wrote:
> > I have to compute some standard errors using the delta
> > method and so have to use the command "numericDeriv"
> > to get the desired gradient. Befor using it on my
> > complicated function, I've done a try with a simple
> > exemple :
> >
> > x <- 1:5
> > numericDeriv(quote(x^2),"x")
> >
> > and i get :
> >
> > [1] 1 8 27 64 125 216
> > attr(,"gradient")
> > [,1] [,2] [,3] [,4] [,5] [,6]
> > [1,] Inf 0 0 NaN 0 0
> > [2,] 0 0 0 NaN 0 0
> > [3,] 0 Inf 0 NaN 0 0
> > [4,] 0 0 0 NaN 0 0
> > [5,] 0 0 Inf NaN 0 0
> > [6,] 0 0 0 NaN 0 0
> >
> > I don't understand the result. I thought I will get :
> >
> > [1] 1 8 27 64 125 216
> > attr(,"gradient")
> > [,1]
> > [1,] 1
> > [2,] 4
> > [3,] 6
> > [4,] 8
> > [5,] 10
> > [6,] 12
> >
> > The derivative of x^2 is still 2x, isn't it ?
>
> The trap you've fallen into is that "x <- 1:5" makes x of
> integer type, and (believe it or not) you cannot differentiate
> when the support of a function is the integers. Wrong topology
> (though I'm not sure that this is quite how R thinks about it).
>
> So give x a bit of elbow-room ("numeric" type has "continous"
> -- well, nearly -- topology):
>
> > x <- as.numeric(1:5)
> > numericDeriv(quote(x^2),"x")
> [1] 1 4 9 16 25
> attr(,"gradient")
> [,1] [,2] [,3] [,4] [,5]
> [1,] 2 0 0 0 0
> [2,] 0 4 0 0 0
> [3,] 0 0 6 0 0
> [4,] 0 0 0 8 0
> [5,] 0 0 0 0 10
Oho. That had me baffled for a while... We should probably also
explain that x is a vector and differentiation of a vector w.r.t. a
vector is a matrix. If you want a 5x1 result you should likely use
something like
> d<-0
> numericDeriv(quote((x+d)^2),"d")
[1] 1 4 9 16 25
attr(,"gradient")
[,1]
[1,] 2
[2,] 4
[3,] 6
[4,] 8
[5,] 10
(I *hope* there's no way to get the result that Florent claims that he
expected...)
--
O__ ---- Peter Dalgaard Øster Farimagsgade 5, Entr.B
c/ /'_ --- Dept. of Biostatistics PO Box 2099, 1014 Cph. K
(*) \(*) -- University of Copenhagen Denmark Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk) FAX: (+45) 35327907
More information about the R-help
mailing list