Search code examples
rlogistic-regression

How to evaluate symbolic derivative as a function in R?


I am able to compute a symbolic derivative in R for the logit function with this statement:

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

The result is an expression:

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

However, when I try to return the expression in a function, such as like this:

DerivLogit <- function(x){
    deriv(expression(exp(-9.3 + 0.0146*x)/(1 + exp(-9.3 + 0.0146*x))),"x")
}

evaluating DerivLogit(x) of course doesn't substitute the parameter x for the variable x in my expression. And so, for example, DerivLogit(1) equals DerivLogit(2), both of which simply return the expression without any parameter substitution.

Is there a way to convert the derivative expression into a function that I can evaluate where the parameter (e.g. x) will substitute so that I can see the numerical outcome for the given value of x? And if so, how do I do so in R?


Solution

  • You can use eval to evaluate the expression

    DerivLogit <- function(x){
      eval(deriv(expression(exp(-9.3 + 0.0146*x)/(1 + exp(-9.3 + 0.0146*x))),"x"))
    }