Calculate Derivative of Expression in R (Example) | deriv() Function
In this article you’ll learn how to compute the derivative of an expression using the deriv() function in the R programming language.
Table of contents:
Let’s get started!
Example: Calculate Derivative of Expression Using deriv() Function
The following syntax demonstrates how to use the deriv command to compute the derivative of an expression.
For this, we first have to apply the deriv function to a formula as shown below:
my_deriv <- deriv(~ x^3 + 2 * x, "x") # Apply deriv function
Furthermore, we have to specify the x value that we want to evaluate (i.e. 3):
x <- 3 # Assign value to x
Next, we can apply the eval function to evaluate our expression:
eval(my_deriv) # Apply eval function # [1] 33 # attr(,"gradient") # x # [1,] 29
As you can see, the eval function has returned the result 33 (i.e. 3^3 + 2 * 3 = 33).
Video & Further Resources
If you need more info on the R programming code of this article, you might want to have a look at the following video on my YouTube channel. In the video, I’m showing the R programming code of this article:
The YouTube video will be added soon.
In addition, you could have a look at some of the other R tutorials on this website:
On this page, I have illustrated how to get the derivative of an expression in the R programming language.
Note that the R programming language provides further functions such as D() and deriv3() to calculate derivatives in R. Have a look at the help documentation of the deriv function (i.e. type ?deriv in the RStudio console) for more details.
If you have any additional questions, let me know in the comments section.
Statistics Globe Newsletter