I want to make a piecewise linear regression in R. I have a large dataset with 3 segments where I want the first and third segment to be without slope, i.e. parallel to x-axis and I also want the regression to be continuous. I have a small example to make piecewise regression with 2 breakpoints and slope1 =0
y <- c(4.5,4.3,2.57,4.40,4.52,1.39,4.15,3.55,2.49,4.27,4.42,4.10,2.21,2.9,1.42,1.5,1.45,1.7,4.6,3.8,1.9)
x<- c(320,419,650,340,400,800,300,570,720,480,425,460,675,600,850,920,975,1022,450,520,780)
plot(x, y, col="black",pch=16)
# slope = 0 before the first breakpoint
a<-lm(y~x)
g<- segmented(a, seg.Z = ~ x, psi=c(400,800))
g
fit.glm<-update(a,.~. -x)
fit.seg1 <- segmented.lm(fit.glm, seg.Z = ~x, psi=c(441.8,817.4))
points(x,fitted(fit.seg1),col=2)
or slope3 = 0
# slope = 0 after the second breakpoint
o<-lm(y~1)
xx<- -x
o2<-segmented(o,seg.Z=~xx,psi=c(-817.4,-441.8))
slope(o2)
points(x,fitted(o2),col=3)
but I can not find how to do slope1=0 and slope 3=0. Do you know if it's possible?