derivatives: Tools for differentiating mathematical functions

Description Usage Arguments Value Examples

Description

Obtain a function's Jacobian (matrix of first partial derivatives) or Hessian (matrix of second partial derivatives).

Usage

1
2
3
get_hessian(f, as_matrix = FALSE, eval_at = NULL)

get_jacobian(f, as_matrix = FALSE, eval_at = NULL)

Arguments

f

A mathematical expression (or list of expressions, if using 'get_jacobian()') generated with the expression function (e.g. expression(y*sin(x)))

as_matrix

Whether to return the symbolic matrix of derivatives as a list of expressions or as a character matrix.

eval_at

A named list giving a point at which the matrix of derivatives is to be evaluated (e.g. list(x = 1, y = 2))

Value

If as_matrix = TRUE, a character matrix showing the symbolic matrix of derivatives. If as_matrix = FALSE, the result is a nested list of expressions. To retrieve the entry in row i column j of the matrix, select hessian_result[[i]][[j]]. If an evaluation point is specified with eval_at, the matrix of derivatives is evaluated and the result is a numeric matrix.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# Create a mathematical expression
fn <- expression(a * log(p/(1-p)))

# Get the symbolic Hessian
## As a nested list
  get_hessian(fn)

## As a character matrix
  get_hessian(fn, as_matrix = TRUE)

# Evaluated the Hessian at a specific point

  get_hessian(fn, eval_at = list(a = 100, p = 0.5))


# Simple vector-valued function giving perimeter and area of a rectangle

vector_valued_fn <- list('perimeter' = expression(2*w + 2*h), 'area' = expression(w * h))

# Get the symbolic Jacobian
## As a nested list
   get_jacobian(vector_valued_fn)

## As a character matrix
   get_jacobian(vector_valued_fn, as_matrix = TRUE)

# Evaluate the Jacobian at a specific point

   get_jacobian(vector_valued_fn, eval_at = list(w = 10, h = 10))

bschneidr/schneidr documentation built on Dec. 25, 2021, 4:55 p.m.