# How To Use deriv In R

In programming, you will occasionally need to calculate the derivative of some expressions. The R language provides a function to perform the derivation work, the deriv() function. This article will share about deriv in R and how to use it. Let’s read it now.

## What is deriv in R?

There are three functions used to calculate the derivative of expressions in R: the functions D(), deriv(), and deriv3().

Syntax:

D(expr, name)

deriv(expr, name)

# Returns a more complex expression object.

deriv3(expr, name)

Parameters:

• expr: an expression or call.
• name: a character vector representing the variable name used to calculate the derivative.

## How to compute derivatives using deriv?

We will give specific examples to illustrate how the deriv() function works.

### Compute derivatives

In this example, I have a ternary expression like this: x^3 + 2*x + 1. I will use the deriv() function to calculate the derivative of this expression.

Example:

# Create an expression
expr <- expression(x ^ 3 + 2 * x + 1)

# Calculate the derivative of the expression
deriv_expr1 <- deriv(expr, "x")
print(deriv_expr1)

# Returns a more detailed result
deriv_expr2 <- deriv3(expr, "x")
print(deriv_expr2)

# Returns the same result
# deriv_expr1 <- deriv(~ x ^ 3 + 2 * x + 1, "x")
# deriv_expr2 <- deriv3(~ x ^ 3 + 2 * x + 1, "x")

Output:

expression({
.value <- x^3 + 2 * x + 1
.grad <- array(0, c(length(.value), 1L), list(NULL, c("x")))
.grad[, "x"] <- 3 * x^2 + 2
.value
})
expression({
.expr2 <- 2 * x
.value <- x^3 + .expr2 + 1
.grad <- array(0, c(length(.value), 1L), list(NULL, c("x")))
.hessian <- array(0, c(length(.value), 1L, 1L), list(NULL,
c("x"), c("x")))
.grad[, "x"] <- 3 * x^2 + 2
.hessian[, "x", "x"] <- 3 * .expr2
attr(.value, "hessian") <- .hessian
.value
})


The deriv() and deriv3() functions return an expression object.

### Higher order derivative

The D() function returns a call so you can use the output for the higher-order derivative.

Example:

# Create an expression
expr <- expression(x ^ 3 + 2 * x + 1)

# Calculate the derivative of the expression
cat("Derivative of the 'expr' expression\n")
deriv_expr1 <- D(expr, "x")
print(deriv_expr1)

# Higher order derivative
cat("\nHigher-order derivative\n")
deriv_expr2 <- D(deriv_expr1, "x")
print(deriv_expr2)

Output:

Derivative of the 'expr' expression
3 * x^2 + 2

Higher-order derivative
3 * (2 * x)


## Summary

We have shared how to calculate the derivative using deriv in R. If you want to use the result obtained to calculate the higher-order derivative, you can use the D() function. Thank you for reading.

Maybe you are interested:

Posted in R