rderivativedifferentiation

Deriv package | Could not retrieve body of 'return()'


I am trying to differentiate the function f_current_theta with respect to current_theta, but the following error is printed:

f_current_theta <- function(current_theta) {
  if(current_theta > 0){
    result <- -log(sqrt(2) * exp(-2*current_theta) / pi * sqrt(current_theta))
    return(result)
  } else {
    result <- -log(0)
    return(result)
  }
}

U_grad <- Deriv::Deriv(f_current_theta)

Error in Deriv_(a, x[ix], env, use.D, dsym, scache, drule. = drule.) : 
  Could not retrieve body of 'return()'

Why it can't retrieve the body of 'return'?


Solution

  • Don't use an explicit return() statement. Also if you vectorize your function, you can use it an argument to curve(). You can do this with ifelse() rather than if():

    f <- function(theta) {
        ifelse(
            theta > 0,
            -log(sqrt(2) * exp(-2*theta) / pi * sqrt(theta)),
            Inf
        )
    }
    
    (df  <- Deriv::Deriv(f))
    # function (theta) 
    # ifelse(test = theta > 0, yes = -(0.5/theta - 2), no = 0)
    

    Then we can plot these:

    p  <- curve(f, from=0, to=2, , xlab="x", ylab="y", ylim = c(-25,25))
    lines(p$x, df(p$x), col = "red")
    

    enter image description here