0

I am to implement this methodology using my data. Fitting known equation to data. How ever I have 6 different equations for different intervals of x.

Below is the function I am using to fit the equations

Func <- function(t,t1,t2,t3,t4,t5,t6,a1,a2,a3,a4,a5,a6,b1,b2,c1,c2,c3,c4,c5,c6){
  if(t<t1){
    t*0
  }
  else if(t>=t1&t<t2){
    a1*t+c1
  }
  else if(t>=t2&t<t3){
    a3*t+c2
  }
  else if(t>=t3&t<t4){
    a3*t+c3
  }
  else if(t>=t4&t<t5){
    a4*t**2 + b1*t+c4
  }
  else if(t>=t5&t<t6){
    a5*t**2 + b2*t+c5
  }
  else if(t>=t6){
    a6*t+c6
  }
}


plot(t,w)
curve(Func(t,1.4,14.4,41.8,60.3,194.3,527,0.0022,0.0029,0.0016,0.00001,0.00001,0.0168,0.0001,-0.0006,0.0063,-0.0433,-0.0022,0.00408,0.2337,-5.3732),add=TRUE)

While executing curve function I am getting an error:

Error in curve(Func(t, 1.4, 14.4, 41.8, 60.3, 194.3, 527, 0.0022, 0.0029,  : 
  'expr' must be a function, or a call or an expression containing 'x'
Community
  • 1
  • 1
Shankar Pandala
  • 969
  • 2
  • 8
  • 28

1 Answers1

1

curve needs a vectorized function and if is not vectorized. You can use ifelse, but it's more readable and efficient to utilize that R can use boolean values in calculations by coercing them to 0/1.

Func <- function(t,t1,t2,t3,t4,t5,t6,a1,a2,a3,a4,a5,a6,b1,b2,c1,c2,c3,c4,c5,c6){
  (t<t1) * t * 0 +
  (t>=t1&t<t2) * (a1*t+c1) +
  (t>=t2&t<t3) * (a3*t+c2) +
  (t>=t3&t<t4) * (a3*t+c3) +
  (t>=t4&t<t5) * (a4*t**2 + b1*t+c4) +
  (t>=t5&t<t6) * (a5*t**2 + b2*t+c5) +
  (t>=t6) * (a6*t+c6)
}


t <- (1:10000)/10
plot(t, t/100)

#you must use x here    
curve(Func(x,1.4,14.4,41.8,60.3,194.3,527,0.0022,0.0029,0.0016,0.00001,0.00001,0.0168,
               0.0001,-0.0006,0.0063,-0.0433,-0.0022,0.00408,0.2337,-5.3732),add=TRUE)

resulting plot

Roland
  • 127,288
  • 10
  • 191
  • 288
  • I am getting error with nls function now nls(w~Func(t,t1,t2,t3,t4,t5,t6,a1,a2,a3,a4,a5,a6,b1,b2,c1,c2,c3,c4,c5,c6), start=list(t1=1.4,t2=14.4,t3=41.8,t4=60.3,t5=194.3, t6=527.0,a1=0.0022,a2=0.0029,a3=0.0016, a4=0.00001,a5=0.00001,a6=0.0168, b1=0.0001,b2=-0.0006,c1=0.0063,c2=-0.0433, c3=-0.0022,c4=0.00408,c5=0.2337,c6=-5.3732)) – Shankar Pandala Mar 03 '17 at 10:29
  • 1
    You should abandon all hope to fit this function using `nls`. – Roland Mar 03 '17 at 10:32
  • Is there any other way to fit the curve ? – Shankar Pandala Mar 03 '17 at 10:33
  • 1
    Maybe something like segmented regression if you have a massive amount of data. – Roland Mar 03 '17 at 11:12