Timothy R. Johnson writes:
>
> Hello all.
>
> I am confused about how deriv() works in comparison to deriv3() (from
> the V&R MASS library). I'm using S-PLUS version 4.5, release 2, for MS
> Windows.
deriv3() may be in the MASS library now, but it is there by kind
permission of the author, David M. Smith, now of MathSoft UK.
> I want to use deriv() to return a function that will give me the
> gradient of a specified function. I try deriv(),
>
> > foo1 <- deriv(z ~ 2*x + 3*y, c("x","y"), function(x,y) {})
> > foo1
> function(x, y)
> {
> .value <- (2 * x) + (3 * y)
> .actualArgs <- match.call()[c("x", "y")]
> if(all(unlist(lapply(as.list(.actualArgs), is.name)))) {
> .grad <- array(0, c(length(.value), 2), list(NULL, c("x", "y")))
> .grad[, "x"] <- 2
> .grad[, "y"] <- 3
> dimnames(.grad) <- list(NULL, .actualArgs)
> attr(.value, "gradient") <- .grad
> }
> .value
> }
> > foo1(1,1)
> [1] 5
> > attr(foo1(1,1), "gradient")
> NULL
It is a bug that was introduced into S-PLUS 4.x and has remained
safely ensconced there ever since, even S-PLUS 5.1 for Unix is
affected. It seems to be a classic case of fixing something that
simply isn't broken.
Inspection of the code that you now get shows that you can work
around it by using only "name" arguments (not "named" arguments):
> x <- 1; y <- 1
> attr(foo1(x, y), "gradient")
x y
[1,] 2 3
but you certainly should not have to pussy-foot around it like
that! More seriously if you put the names the other way round
you get the labels in the output switched:
> attr(foo1(y, x), "gradient")
y x
[1,] 2 3
which to my mind confuses variables with their values.
deriv3() continues to work because it merely extends the old,
unbroken version of deriv(). We failed to introduce the bug in
question for some reason. Perhaps we were just too slow....
--
Bill Venables, Statistician, CMIS Environmetrics Project
CSIRO Marine Labs, PO Box 120, Cleveland, Qld, AUSTRALIA. 4163
Tel: +61 7 3826 7251 Email: Bill.Venables@cmis.csiro.au
Fax: +61 7 3826 7304 http://www.cmis.csiro.au/bill.venables/
-----------------------------------------------------------------------
This message was distributed by s-news@wubios.wustl.edu. To unsubscribe
send e-mail to s-news-request@wubios.wustl.edu with the BODY of the
message: unsubscribe s-news
|