I am trying to do a piecewise linear OLS regression analysis in R, with one breakpoint. I have the following regression formula and restrictions:
Where D is a dummy. I would like to impose a restriction, so that the regression lines are continous (with a break point). The restriction below would work fine.
My question is, how do I formulate that in the lm()-function in R? I have previously tried the "segmented" package, but I need to interpret the intercepts for both lines in a regression summary.
I have provided some data below. The breakpoint here is 0, so d
is 1 for x >= 0 .
x y d
1 4.3047451 11.2660463 1
2 7.0062423 -3.2897982 1
3 2.7862009 -2.8232636 1
4 -0.8662964 0.4051925 0
5 -0.9553261 -0.9228929 0
6 -1.6626654 3.5044546 0
7 3.4906905 1.4961349 1
8 -0.7072658 -0.2758436 0
9 -7.0054069 -1.3041742 0
10 -2.2510701 -0.1848814 0
11 -13.3617905 -0.2113756 0
12 4.1001251 0.2845748 1
13 -4.6575944 -1.1603290 0
14 5.2243857 3.8324236 1
15 3.5003320 -2.3672985 1
16 -13.2623113 -7.1593177 0
17 -1.7944354 -2.1725478 0
18 0.5885924 -0.2411048 1
19 -19.3744936 -0.1982088 0
20 -17.9876978 -1.5995063 0
Edit:
I have added a graphic representation of what I am trying to perform. It is important that the 2 fitted lines meet at the threshold, and that I can get 4 coefficents. 2 alphas, and 2 betas.
Since the breakpoint is x = 0 we have a = a2 and so:
nls( y ~ (x < 0) * (a + b * x) + (x > 0) * (a + b2 * x), dat,
start = list(a = 1, b = 1, b2 = 1))
or using lm
lm(y ~ I(x * (x < 0)) + I(x * (x > 0)), dat)
In general if B is the breakpoint:
B <- 0
nls( y ~ (x < B) * (a + b * (x - B)) + (x > B) * (a + b2 * (x - B)), dat,
start = list(a = 1, b = 1, b2 = 1))
B <- 0
lm(y ~ I((x - B) * (x < B)) + I((x - B) * (x > B)), dat)
This is not an answer but a comment which cannot be edited in the comments section because it requires an image to be understandable.
In fact, I cannot understand your data : When represented on Cartesian graph (below) the points appear very scattered. It doesn't look like a piecewise function. What am I missing ?
By the way, if the points were not too far from a piecewise function made of two inclined segments, there is a very simple method for the fitting. See pages 12-13 in this paper : https://fr.scribd.com/document/380941024/Regression-par-morceaux-Piecewise-Regression-pdf
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.