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