[R] Deriving formula with deriv

David Winsemius dwinsemius at comcast.net
Mon Apr 4 17:22:33 CEST 2011


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



More information about the R-help mailing list