Segmented Package in R – How to Fit Piecewise Linear Regression with One Breakpoint?

piecewise linearrregression

I have problems using the package segmented.

My linear regression is very simple, between offer and demand:

linearModel <- lm(demand~offer)

And so should be my model using "segmented":

piecewiseModel <- segmented(lm(demand~offer), seg.Z = ~ offer, psi = NA)

But I have an error message and I really cannot find a reason for this:

Error in seg.lm.fit(y, XREG, Z, PSI, weights, offs, opz) : 
  (Some) estimated psi out of its range

Here are my data:

demand  offer
1155    39.3
362 23.5
357 22.4
111 6.1
703 35.9
494 35.5
410 23.2
63  9.1
616 27.5
468 28.6
973 41.3
235 16.9
180 18.2
69  9
305 28.6
106 12.7
155 11.8
422 27.9
44  21.6
1008    45.9
225 11.4
321 16.6
1001    40.7
531 22.4
143 17.4
251 14.3
216 14.6
57  6.6
146 10.6
226 14.3
169 3.4
32  5.1
75  4.1
102 4.1
4   1.7
68  7.5
102 7.8
462 22.6
295 8.6
196 7.7
50  7.8
739 34.7
287 15.6
226 18.5
706 35
127 16.5
85  11.3
234 7.7
153 14.8
4   2
373 12.4
54  9.2
81  11.8
18  3.9

Best Answer

It appears that what is happening is that one of the estimates for a breakpoint is moving outside the range of offer during the fitting procedure. (You can deduce this by typing seg.lm.fit at the prompt and fighting your way through the code.) You can work around this by specifying PSI, the starting values for the breakpoints. I also set seg.control=list(stop.if.error=FALSE) to try to work around the problem, but that didn't help.

I reran your model with PSI=c(15) and it worked, but with PSI=c(15,25) I got an iteration count exceeded error message, which I could not overcome even by setting the maximum number of iterations to 1,000. I would take this as meaning that one breakpoint is all you're going to be able to estimate with this function and data.

As an extra note, if you plot(sqrt(demand)~offer), the relationship looks a lot closer to linear than just demand~offer, so you might want to try a transform of the data rather than a piecewise linear model.

Related Question