[英]How to write a (first-order) derivative as a function in R?
I need the derivative of pt*(p^g)*(1-p)^d) as a function of p. 我需要pt *(p ^ g)*(1-p)^ d)的导数作为p的函数。 t,d and g are all defined.
t,d和g都是定义的。 I was trying:
我在努力:
firstder<-D(expression(p-t*(p^g)*(1-p)^d), "p")
firstderivative<-function(p){
firstder
}
However, calling 然而,打电话
firstderivative(p=0.1)
gives me nothing more than the expression of the first derivative. 我只给出了一阶导数的表达。 Thanks in advance!
提前致谢!
firstder
is an object of class "call"
. firstder
是类"call"
的对象。
class(firstder)
#[1] "call"
You are forgetting to evaluate the call. 你忘记评估电话了。
firstder <- D(expression(p-t*(p^g)*(1-p)^d), "p")
firstderivative <- function(p){
eval(firstder)
}
g <- 1
d <- 1
t <- 1
firstderivative(p=0.1)
#[1] 0.2
It is very easy using mosaicCore
package. 使用
mosaicCore
包很容易。 Given that you have F(x)=x^2
and you wish to calculate the derivative based on x
so you have: 鉴于您有
F(x)=x^2
并且您希望基于x
计算导数,所以您有:
library(mosaicCore)
dx2x <- deriv(~ x^2, "x")
x <- -1:2
eval(dx2x)
In your case, it would be: 在你的情况下,它将是:
library(mosaicCore)
dx <- deriv(~expression(p-t*(p^g)*(1-p)^d), "p")
x <- -1:2
eval(dx)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.