deriv3 is a generic function which takes the first and
optionally second partial derivative of an S expression
with respect to a given variable or variables.
deriv3(expr, namevec, function.arg, tag=".expr",
hessian = T)
function.arg is given as a function prototype, the
function arguments can have defaults.
gradient and
hessian, if
requested. This is the gradient matrix and Hessian 3-way array of the
expression value with respect to the named parameters.
This function is an extension of
deriv, using a similar
method. See
deriv for precise details.
# A zero-truncated Poisson negative log-likelihood
deriv3(~- y*(a+b*x) + exp(a+b*x) + log(1-exp(-exp(a+b*x))),
c("a","b"), function(y, x, a, b){})
function(y, x, a, b)
{
.expr3 <- a + (b * x)
.expr5 <- exp(.expr3)
.expr8 <- exp(( - .expr5))
.expr9 <- 1 - .expr8
.expr13 <- .expr8 * .expr5
.expr20 <- .expr9^2
.expr24 <- .expr5 * x
.expr25 <- .expr8 * .expr24
.expr32 <- .expr24 + (((.expr25 - (.expr25 * .expr5))/
.expr9) - ((.expr13 * .expr25)/.expr20))
.expr37 <- .expr24 * x
.value <- ((( - y) * .expr3) + .expr5) + (log(.expr9))
.grad <- array(0, c(length(.value), 2), list(NULL, c("a",
"b")))
.hess <- array(0, c(length(.value), 2, 2), list(NULL, c(
"a", "b"), c("a", "b")))
.grad[, "a"] <- (.expr5 - y) + (.expr13/.expr9)
.grad[, "b"] <- (.expr24 - (y * x)) + (.expr25/.expr9)
.hess[, "a", "a"] <- .expr5 + (((.expr13 - (.expr13 *
.expr5))/.expr9) - ((.expr13 * .expr13)/.expr20)
)
.hess[, "b", "a"] <- .expr32
.hess[, "a", "b"] <- .expr32
.hess[, "b", "b"] <- .expr37 + ((((.expr8 * .expr37) - (
.expr25 * .expr24))/.expr9) - ((.expr25 *
.expr25)/.expr20))
attr(.value, "gradient") <- .grad
attr(.value, "hessian") <- .hess
.value
}