Consider the example of help(segmented)
To adjust the segmented regression model, you first need to adjust the linear regression model.
set.seed(12)
xx<-1:100
zz<-runif(100)
yy<-2+1.5*pmax(xx-35,0)-1.5*pmax(xx-70,0)+15*pmax(zz-.5,0)+rnorm(100,0,2)
dati<-data.frame(x=xx,y=yy,z=zz)
out.lm<-lm(y~x,data=dati)
The segmented
function always estimates the breakpoints. If you provide initial values via the psi
parameter, the number of breakpoints it estimates is the same as the size of the vector you passed.
> m.s <- segmented(m, seg.Z = ~x, psi = c(25, 80))
> m.s
Call: segmented.lm(obj = m, seg.Z = ~x, psi = c(25, 80))
Meaningful coefficients of the linear terms:
(Intercept) x z U1.x U2.x
1.12868 -0.06976 8.72782 1.55907 -1.54130
Estimated Break-Point(s):
psi1.x psi2.x
34.37 70.56
See estimated values for breakpoints above.
You can also provide no initial value ( psi = NA
), and in this case provide only the number of breakpoints you want to use via the K
parameter in the seg.control
function.
> m.s <- segmented(m, seg.Z = ~x, psi = NA, control = seg.control(K = 2))
> m.s
Call: segmented.lm(obj = m, seg.Z = ~x, psi = NA, control = seg.control(K = 2))
Meaningful coefficients of the linear terms:
(Intercept) x z U1.x U2.x
1.11308 -0.06832 8.72422 1.55716 -1.54335
Estimated Break-Point(s):
psi1.x psi2.x
34.39 70.61
Note that the default value of K
is 10 and so if your database does not have as many change points, you will have estimation problems if you do not provide K
.