| deriv {base} | R Documentation |
Compute derivatives of simple expressions, symbolically.
D (expr, name) deriv(expr, namevec, function.arg = NULL, tag = ".expr")
expr |
expression or call which should
be differentiated. |
name,namevec |
character vector, giving the variable names (only
one for D(.)) with
respect to which derivatives will be computed. |
function.arg |
If specified, a character vector of arguments for a function return. Note: this is incompatible with S. |
tag |
character; the prefix to be used for the locally created variables in result. |
D is modelled after its S namesake for taking simple symbolic
derivatives.
deriv is a generic function with a default and a
formula method. It returns a call for
computing the expr and its (partial) derivatives,
simultaneously. It uses so-called ``algorithmic
derivatives''.
Currently, deriv.formula just calls deriv.default after
extracting the expression to the right of ~.
D returns a call and therefore can easily be iterated
for higher derivatives.
deriv normally returns an expression object.
Its evaluation returns the function values with a
".gradient" attribute containing the gradient matrix.
If function.arg is specified, it returns a function.
This help page should be fixed up by one of R&R or someone else who fluently speaks the language in `$R_HOME/src/main/deriv.c'.
Its author, MM, has only got a vague idea and thinks that a help page is better than none.
Griewank, A. and Corliss, G. F. (1991) Automatic Differentiation of Algorithms: Theory, Implementation, and Application. SIAM proceedings, Philadelphia.
nlm and optim for numeric minimization
which could make use of derivatives,
nls in package nls.
## formula argument :
dx2x <- deriv(~ x^2, "x") ; dx2x
expression({
.value <- x^2
.grad <- array(0, c(length(.value), 1), list(NULL, c("x")))
.grad[, "x"] <- 2 * x
attr(.value, "gradient") <- .grad
.value
})
mode(dx2x)
x <- -1:2
eval(dx2x)
## Something `tougher':
trig.exp <- expression(sin(cos(x + y^2)))
( D.sc <- D(trig.exp, "x") )
all.equal(D(trig.exp[[1]], "x"), D.sc)
( dxy <- deriv(trig.exp, c("x", "y")) )
y <- 1
eval(dxy)
eval(D.sc)
stopifnot(eval(D.sc) ==
attr(eval(dxy),"gradient")[,"x"])
## function returned:
deriv(y ~ b0 + b1 * 2^(-x/th), c("b0", "b1", "th"),
c("b0", "b1", "th", "x") )
## Higher derivatives:
DD <- function(expr,name, order = 1) {
if(order < 1) stop("`order' must be >= 1")
if(order == 1) D(expr,name)
else DD(D(expr, name), name, order - 1)
}
DD(expression(sin(x^2)), "x", 3)
## showing the limits of the internal "simplify()" :
-sin(x^2) * (2 * x) * 2 + ((cos(x^2) * (2 * x) * (2 * x) + sin(x^2) *
2) * (2 * x) + sin(x^2) * (2 * x) * 2)