简体   繁体   中英

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. t,d and g are all defined. 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" .

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. Given that you have F(x)=x^2 and you wish to calculate the derivative based on x so you have:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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