Symbolic Partial Derivatives of Expressions

DESCRIPTION:

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.

USAGE:

deriv3(expr, namevec, function.arg, tag=".expr",  
       hessian = T) 

REQUIRED ARGUMENTS:

expr
expression to be differentiated, typically a formula, in which case the function returned computes the right side of the ~ and its derivatives.
namevec
character vector of names of the parameters for which derivatives are required.

OPTIONAL ARGUMENTS:

function.arg
optional argument vector or prototype for a function. If present, the returned value is in the form of a function instead of a multiple statement expression. When function.arg is given as a function prototype, the function arguments can have defaults.
tag
base of the names to be given to intermediate results.
hessian
logical value indicating whether second derivatives are to be computed.

VALUE:

a multiple-statement expression or a function definition. When evaluated, these statements return the value of the original expression along with attributes called 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.

DETAILS:

This function is an extension of deriv, using a similar method. See deriv for precise details.

SEE ALSO:

EXAMPLES:

# 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 
}