s-news
[Top] [All Lists]

[S] deriv versus deriv3

To: s-news@wubios.wustl.edu
Subject: [S] deriv versus deriv3
From: "Timothy R. Johnson" <trjohns@pullman.com>
Date: Wed, 23 Feb 2000 18:21:17 -0800
Organization: Department of Psychology
Sender: owner-s-news@wubios.wustl.edu
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.

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

and no gradient! Where did it go? With deriv3() I get

> foo2 <- deriv3(z ~ 2*x + 3*y, c("x","y"), function(x,y) {})
> foo2
function(x, y)
{
 .expr5 <- 0
 .value <- (2 * x) + (3 * y)
 .grad <- array(0, c(length(.value), 2), list(NULL, c("x", "y")))
 .hess <- array(0, c(length(.value), 2, 2), list(NULL, c("x", "y"),
c("x", "y")))
 .grad[, "x"] <- 2
 .grad[, "y"] <- 3
 .hess[, "x", "x"] <- .expr5
 .hess[, "y", "x"] <- .expr5
 .hess[, "x", "y"] <- .expr5
 .hess[, "y", "y"] <- .expr5
 attr(.value, "gradient") <- .grad
 attr(.value, "hessian") <- .hess
 .value
}
> foo2(1,1)
[1] 5
attr(, "gradient"):
     x y
[1,] 2 3
attr(, "hessian"):

, , x
     x y
[1,] 0 0

, , y
     x y
[1,] 0 0
> attr(foo2(1,1), "gradient")
     x y
[1,] 2 3

which is fine. I don't understand why the function foo1 given by
deriv() does not work in the way it seems it should.

I would use deriv3() but I do not need the hessian and therefore do
not want to use up CPU time doing so. Of course, I could edit the
function to remove the hessian computations but it seems like I should
be able to get deriv() to do what I want.

Am I confused about how deriv() does/should work. Any feedback would
be very much appreciated.

Best regards,

Tim

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Timothy R. Johnson
Division of Quantitative Psychology
Department of Psychology
University of Illinois @ Urbana-Champaign
mailto:tjohnson@s.psych.uiuc.edu
http://www.psych.uiuc.edu/~tjohnson/tjohnson.html


-----------------------------------------------------------------------
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

<Prev in Thread] Current Thread [Next in Thread>