[R] nls and discontinuous functions

Gabor Grothendieck ggrothendieck at gmail.com
Fri Nov 30 15:49:23 CET 2007


Vectorize f using ifelse in place of if:

> f <- function (t,k,l,u) {
+ r0 <- 346.1
+ x<- t-l
+ ifelse(x < 0, r0, (r0-u)*exp(-k*x)+u)
+ }
>
> prof1 = data.frame(
+ t = c(0, 3, 6, 12, 18, 24, 36, 48, 72, 96),
+ y1 = c(346.12, 343.13, 327.44, 280.95, 242.76, 228.67,
+        193.48, 174.29, 164.81, 152)
+ )
>
> nls(y1 ~ f(t,k,l,u), data=prof1, start=list(k=0.05, l=4, u=154))
Nonlinear regression model
  model:  y1 ~ f(t, k, l, u)
   data:  prof1
        k         l         u
  0.04981   3.76690 154.04375
 residual sum-of-squares: 102.2

Number of iterations to convergence: 3
Achieved convergence tolerance: 2.862e-06
>

On Nov 30, 2007 9:25 AM, Luis Orlindo Tedeschi
<luis.tedeschi at hotmail.com> wrote:
> Folks; I have looked for this subject extensively using all the resources I have available and could not find a solution; therefore I am sending you this email seeking for help. I need to solve a discontinuous nonlinear function, but R 2.6 keeps giving me an error. Below is a simple example:
>
> f <- function (t,k,l,u) { r0<-346.1 x<-t-l if (x<0)  r0 else  (r0-u)*exp(-k*x)+u }prof1<-read.table("c:\\data.txt", header=TRUE)results<-nls(y1~f1(t,k,l,u), data=prof1, start=list(k=0.05, l=4, u=154))
>
> Errors I am getting are:
>
>
> Error in qr(.swts * attr(rhs, "gradient")) :   dims [product 3] do not match the length of object [10]In addition: Warning messages:1: In if (x < 0) r0 else (r0 - u) * exp(-k * x) + u :  the condition has length > 1 and only the first element will be used2: In if (x < 0) r0 else (r0 - u) * exp(-k * x) + u :  the condition has length > 1 and only the first element will be used3: In if (x < 0) r0 else (r0 - u) * exp(-k * x) + u :  the condition has length > 1 and only the first element will be used4: In if (x < 0) r0 else (r0 - u) * exp(-k * x) + u :  the condition has length > 1 and only the first element will be used5: In if (x < 0) r0 else (r0 - u) * exp(-k * x) + u :  the condition has length > 1 and only the first element will be used6: In .swts * attr(rhs, "gradient") :  longer object length is not a multiple of shorter object length
> Data file is this one
>
>
>    t    y1
> 1   0 346.12   3 343.13   6 327.44  12 280.95  18 242.76  24 228.67  36 193.48  48 174.29  72 164.810 96 152.0
>
>
> Any help?
>
> Thanks a lot
>
> Luis
> _________________________________________________________________
>
>
> PC_MediaCtr_bigscreen_102007
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> 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.
>



More information about the R-help mailing list