Re: [R] Deriving formula with deriv

From: David Winsemius <dwinsemius_at_comcast.net>
Date: Mon, 04 Apr 2011 11:22:33 -0400

On Apr 4, 2011, at 6:35 AM, kitty wrote:

> Dear list,
>
> Hi,
>
> I am trying to get the second derivative of a logistic formula, in R
> summary
> the model is given as :
>
> ###
>> $nls
>> Nonlinear regression model
>> model: data ~ logistic(time, A, mu, lambda, addpar)
>> data: parent.frame()
>> A mu lambda
>> 0.53243 0.03741 6.94296
> ###
>
> but I know the formula used is
>
> # y~'A'/(1+exp((4*'mu'/'A')*('lambda'-'time'))+2)) # from the
> grofit (
> package I am using to fit the model) documentation.
>
> I have attempted to use the R function 'deriv' to get the
> first derivative from which I can then reuse the deriv function to
> get the
> second derivative.... unfortunately this does not seem to work
>
> ###
>> express<-expression(y~'A'/(1+exp((4*'mu'/'A')*('lambda'-'time'))+2))
>> express
> expression(y ~ "A"/(1 + exp((4 * "mu"/"A") * ("lambda" - "time")) +
> 2))
>>
>> d1<-deriv(express)
> Error in deriv.default(express) : element 2 is empty;
> the part of the args list of '.Internal' being evaluated was:
> (expr, namevec, function.arg, tag, hessian)
> ####

For one thing you are not specifying what variable you want to differentiate with-respect-to: Assuming this to be `A` then:

  express <-

      expression( A/(1+exp((4*mu/A)*(lambda-time))+ 2))   # The quotes looked "wrong" inside an expression, so I removed them

  d1<-deriv(express, "A") # but the diff w.r.t variable needs to be quoted.

   d1
expression({

     .expr1 <- 4 * mu
     .expr3 <- lambda - time
     .expr5 <- exp(.expr1/A * .expr3)
     .expr7 <- 1 + .expr5 + 2
     .value <- A/.expr7
     .grad <- array(0, c(length(.value), 1L), list(NULL, c("A")))
     .grad[, "A"] <- 1/.expr7 + A * (.expr5 * (.expr1/A^2  
* .expr3))/.expr7^2
     attr(.value, "gradient") <- .grad
     .value

})

All this should have been clear if you had looked at the examples in help(deriv).

>
> Why is this not working and how do I get the second derivative?

That , too, is clearly exemplified in the help page.

>
> Thank you for reading my post, all help is appreciated,
> Kitty

-- 
David Winsemius, MD
West Hartford, CT

______________________________________________
R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Received on Mon 04 Apr 2011 - 15:25:56 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Mon 04 Apr 2011 - 15:50:26 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive