How to create a derivative function?

Viewed 38

I was trying to create a function to derive an expression and the command gives the error below. Can anybody help me ?

derivada<- function(x){

  expression(x)

  z <- D(x,"x")

  print(z)
  
} 

derivada(x^2)

Error in D(x, "x") : object 'x' not found
1 Answers

Something like

derivada <- function(x) D(substitute(x), "x")
derivada(x^2)
## 2 * x
  • the main point here is that substitute(x) captures the expression that was passed as an argument without attempting to evaluate it. (Dealing with expressions and controlling when they get evaluated is tricky.)
  • I had the function return an expression (which then gets auto-printed) rather than printing the result
  • I didn't use curly brackets because the function only takes one expression (although arguably using curly brackets anyway would be better practice)
Related