Search code examples
rlogistic-regressionderivative

How to compute symbolic derivative of logit function?


I'm trying to compute a symbolic derivative in R of the logit function, but I'm getting errors. When I run:

deriv(exp(-9.3 + 0.0146*x)/(1 + exp(-9.3 + 0.0146*x)), x)

I get:

Error in deriv.default(exp(-9.3 + 0.0146 * x)/(1 + exp(-9.3 + 0.0146 * : invalid variable names

When I tried setting my function to logit1(x) and ran: deriv(logit1(x),x) I similarly got:

Error in deriv.default(logit1(x), x) : invalid variable names

as expected.

Any suggestions?


Solution

  • The first argument to deriv has to be a quoted expression, and the second argument is a string giving the name of the variable.

    deriv(quote(exp(-9.3 + 0.0146*x)/(1 + exp(-9.3 + 0.0146*x))), "x")
    #expression({
    #    .expr4 <- exp(-9.3 + 0.0146 * x)
    #    .expr5 <- 1 + .expr4
    #    .expr7 <- .expr4 * 0.0146
    #    .value <- .expr4/.expr5
    #    .grad <- array(0, c(length(.value), 1L), list(NULL, c("x")))
    #    .grad[, "x"] <- .expr7/.expr5 - .expr4 * .expr7/.expr5^2
    #    attr(.value, "gradient") <- .grad
    #    .value