[R] Partial Derivatives in R
Paul Heinrich Dietrich
paul.heinrich.dietrich at gmail.com
Mon May 11 02:12:13 CEST 2009
Thank you for suggesting other functions, I will look into them.
When I read the deriv() function, it did mention partial, but I (being a
newbie) wasn't able to get partials for a simple MNL equation. I'm sure I
did something wrong then, but here's what I tried the following and got
different answers, concluding prematurely maybe that deriv actually just
gives regular derivatives. Thanks for looking:
### Variables for an observation
x01 <- rnorm(1,0,1)
x02 <- rnorm(1,0,1)
### Parameters for an observation
b00.1 <- rnorm(1,0,1)
b00.2 <- rnorm(1,0,1)
b00.3 <- 0
b01.1 <- rnorm(1,0,1)
b01.2 <- rnorm(1,0,1)
b01.3 <- 0
b02.1 <- rnorm(1,0,1)
b02.2 <- rnorm(1,0,1)
b02.3 <- 0
### Predicted Probabilities for an observation
phat1 <- 0.6
phat2 <- 0.3
phat3 <- 0.1
### Correct way to calculate a partial derivative
for MNL
partial.b01.1 <- phat1 * (b01.1 - (b01.1*phat1+b01.2*phat2+b01.3*phat3))
partial.b01.2 <- phat2 * (b01.2 - (b01.1*phat1+b01.2*phat2+b01.3*phat3))
partial.b01.3 <- phat3 * (b01.3 - (b01.1*phat1+b01.2*phat2+b01.3*phat3))
partial.b01.1; partial.b01.2; partial.b01.3
partial.b02.1 <- phat1 * (b02.1 - (b01.1*phat1+b01.2*phat2+b01.3*phat3))
partial.b02.2 <- phat2 * (b02.2 - (b01.1*phat1+b01.2*phat2+b01.3*phat3))
partial.b02.3 <- phat3 * (b02.3 - (b01.1*phat1+b01.2*phat2+b01.3*phat3))
partial.b02.1; partial.b02.2; partial.b02.3
### Derivatives for MNL
according to (my interpretation of) the deriv() function
dp1.dx <- deriv(phat1 ~ exp(b00.1+b01.1*x01+b02.1*x02) /
(exp(b00.1+b01.1*x01+b02.1*x02)+exp(b00.2+b01.2*x01+b02.2*x02)+
exp(b00.3+b01.3*x01+b02.3*x02)), c("x01","x02"))
dp2.dx <- deriv(phat2 ~ exp(b00.2+b01.2*x01+b02.2*x02) /
(exp(b00.1+b01.1*x01+b02.1*x02)+exp(b00.2+b01.2*x01+b02.2*x02)+
exp(b00.3+b01.3*x01+b02.3*x02)), c("x01","x02"))
dp3.dx <- deriv(phat3 ~ exp(b00.3+b01.3*x01+b02.3*x02) /
(exp(b00.1+b01.1*x01+b02.1*x02)+exp(b00.2+b01.2*x01+b02.2*x02)+
exp(b00.3+b01.3*x01+b02.3*x02)), c("x01","x02"))
attr(eval(dp1.dx), "gradient")
attr(eval(dp2.dx), "gradient")
attr(eval(dp3.dx), "gradient")
--
View this message in context: http://www.nabble.com/Partial-Derivatives-in-R-tp23470413p23475411.html
Sent from the R help mailing list archive at Nabble.com.
More information about the R-help
mailing list