[R] deriv value revised question

Douglas Bates bates at stat.wisc.edu
Tue May 22 22:56:06 CEST 2001


"Martin Henry H. Stevens" <hstevens at rci.rutgers.edu> writes:

> Is the simplest way to get eval( deriv(~F,"x") ) to return ONLY the values
> of the
> derivative of F evaluated at x by using
> 
> attr( eval( deriv( ~F, "x" ) ), "gradient") ?
> 
> If so, what is the rationale behind this?
> 
> Many thanks in advance for the edification,

The deriv function was designed to produce functions to use as models
in nls and nlm.  In those cases you often want both the model function
and the gradient array.  If you evaluate the expressions for the model
and for each column of the gradient array at the same time you can
make the evaluation more efficient by eliminating common
subexpressions.  In many cases you can evaluate all of these for
nearly the same cost as evaluating any one.

The savings in an interpreted language like R are magnified because
you save the interpreter cost as well as the arithmetic cost if you
evaluate the subexpressions only once.

In the Michaelis-Menten model, for example,

> deriv(~ Vm*x/(K + x), c("Vm", "K"))
expression({
    .expr1 <- Vm * x
    .expr2 <- K + x
    .value <- .expr1/.expr2
    .grad <- array(0, c(length(.value), 2), list(NULL, c("Vm", 
        "K")))
    .grad[, "Vm"] <- x/.expr2
    .grad[, "K"] <- -.expr1/.expr2^2
    attr(.value, "gradient") <- .grad
    .value
})

the expressions .expr1 and .expr2 are used in several places.  (If you
look carefully you will discover that there could be more elimination
of subexpressions done in this example.  Our algorithm for doing this
is not terribly sophisticated.)
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list