How can I get derivative value in R?

Viewed 15286

I want to get the derivative value from the function below when x = 2. Is there way to keep the form of the function and also get derivative value with out any additional package?

f <- function(x)
  return(x^3)

For example, I have tried below but they didn't work.

x=2
deriv(~f, "x")

x=2
deriv(~body(f),"x")

x=2
D(expression(f),"x")
2 Answers

This would be approximation

foo = function(x, delta = 1e-5, n = 3){
    x = seq(from = x - delta, to = x + delta, length.out = max(2, n))
    y = x^3
    mean(diff(y)/diff(x))
}

foo(2)
#[1] 12
Related