Functions nlsDeriv and codeDeriv are designed as replacements
for the stats package functions D and deriv
respectively, though the argument lists do not match exactly.
The nlsDeriv function computes a symbolic derivative of an expression
or language object. Known derivatives are stored in
derivEnv; the default sysDerivs contains expressions for
all of the derivatives recognized by deriv, but in
addition allows differentiation with respect to any parameter
where it makes sense. It also allows the derivative of abs
and sign, using an arbitrary choice of 0 at the discontinuities.
The codeDeriv function computes
an expression for efficient calculation of the expression value together
with its gradient and optionally the Hessian matrix.
The fnDeriv function wraps the codeDeriv result
in a function. If the args are given as a character
vector (the default), the arguments will have those names,
with no default values. Alternatively, a custom argument list with default values can
be created using alist; see the example below.
The expr argument will be converted to a
language object using dex (but note
the different default for do_substitute).
Normally it should be a formula with no left
hand side, e.g. ~ x^2 , or an expression vector
e.g. expression(x, x^2, x^3) , or a language
object e.g. quote(x^2). In codeDeriv and
fnDeriv the expression vector must be of length 1.
The newDeriv function is used to define a new derivative.
The expr argument should match the header of the function as a
call to it (e.g. as in the help pages), and the deriv argument
should be an expression giving the derivative, including calls to
D(arg), which will not be evaluated, but will be substituted
with partial derivatives of that argument with respect to name.
See the examples below.
If expr or deriv is missing in a call to
newDeriv(), it will return the currently saved derivative
record from derivEnv. If name is missing in a call to
nlsDeriv with a function call, it will print a message describing
the derivative formula and return NULL.
To handle functions which act differently if a parameter is
missing, code the default value of that parameter to .MissingVal,
and give a derivative that is conditional on missing()
applied to that parameter. See the derivatives of "-" and "+"
in the file derivs.R for an example.