简体   繁体   English

如何将符号导数评估为R中的函数?

[英]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: 我可以使用以下语句为logit函数计算R中的符号导数:

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. 评估DerivLogit(x)当然不能用参数x代替表达式中的变量x。 And so, for example, DerivLogit(1) equals DerivLogit(2), both of which simply return the expression without any parameter substitution. 因此,例如,DerivLogit(1)等于DerivLogit(2),两者都简单地返回表达式而无需任何参数替换。

Is there a way to convert the derivative expression into a function that I can evaluate where the parameter (eg x) will substitute so that I can see the numerical outcome for the given value of x? 有没有一种方法可以将导数表达式转换为可以评估参数(例如x)在哪里替换的函数,以便可以看到给定x值的数值结果? And if so, how do I do so in R? 如果是这样,我该如何在R中这样做?

You can use eval to evaluate the expression 您可以使用eval评估表达式

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM