# Compute Derivative of an Expression in R Programming – deriv() and D() Function

In R programming, derivative of a function can be computed using `deriv()` and `D()` function. It is used to compute derivatives of simple expressions.

Syntax:
deriv(expr, name)
D(expr, name)

Parameters:
expr: represents an expression or a formula with no LHS
name: represents character vector to which derivatives will be computed

Example 1:

 `# Expression or formula ` `f = ``expression``(x^2 + 5*x + 1) ` ` `  `# Derivative ` `cat``(``"Using deriv() function:\n"``) ` `print``(``deriv``(f, ``"x"``)) ` ` `  `cat``(``"\nUsing D() function:\n"``) ` `print``(``D``(f, ``'x'``)) `

Output:

```Using deriv() function:
expression({
.value <- x^2 + 5 * x + 1
.grad <- array(0, c(length(.value), 1L), list(NULL, c("x")))
.grad[, "x"] <- 2 * x + 5
.value
})

Using D() function:
2 * x + 5
```

Example 2:

 `# Little harder derivative ` ` `  `# Using deriv() Function ` `cat``(``"Using deriv() function:\n"``) ` `print``(``deriv``(``quote``(``sinpi``(x^2)), ``"x"``)) ` ` `  `# Using D() Function ` `cat``(``"\nUsing D() function:\n"``) ` `print``(``D``(``quote``(``sinpi``(x^2)), ``"x"``)) `

Output:

```Using deriv() function:
expression({
.expr1 <- x^2
.value <- sinpi(.expr1)
.grad <- array(0, c(length(.value), 1L), list(NULL, c("x")))
.grad[, "x"] <- cospi(.expr1) * (pi * (2 * x))
.value
})

Using D() function:
cospi(x^2) * (pi * (2 * x))
```
My Personal Notes arrow_drop_up Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :

Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.