7

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")
d.b
  • 32,245
  • 6
  • 36
  • 77
user8878064
  • 71
  • 1
  • 1
  • 3
  • 1
    Are you asking how to express the derivative of `x^3` (_i.e._ `3x^2`) and then evaluate that for `x = 2` ? – neilfws Nov 03 '17 at 02:12
  • 1
    You could look into using the [Deriv package](https://cran.r-project.org/web/packages/Deriv/Deriv.pdf) which seems to support numerical derivatives. – Tim Biegeleisen Nov 03 '17 at 02:13

2 Answers2

11

You can use deriv, however, one caveat is that you can only use expressions/calls.

derivative = deriv(~ x^3, "x") 
x <- 2
eval(derivative )

With a named expression:

f = expression(x^3)
dx2x <- D(f,"x")

and the rest is the same.

See this link for the documentation: https://www.rdocumentation.org/packages/Deriv/versions/3.8.2/topics/Deriv

Community
  • 1
  • 1
information_interchange
  • 2,538
  • 6
  • 31
  • 49
7

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
d.b
  • 32,245
  • 6
  • 36
  • 77