Search code examples
rfunctionderivative

How to write a (first-order) derivative as a function in R?


I need the derivative of p-t*(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!


Solution

  • 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