Suppose that we have, say 10 values of a predictor $x_{1}$ and we want fit a piecewise linear model of the outcome $y$ vs $x$ in the following way: $Y_{i} =\beta_{0}+\beta_{1}x_{i1}+\epsilon _{i}$ for $i=1,2,3,4,5$ and $Y_{i} = \beta_{0}'+\beta_{1}'x_{i1}+\epsilon_{i}$ for $i=6,7,8,9,10$. I want to write an $R$ code for it. My first intuition is just to regress $y[1:5]$~$x[1:5]$ and $y[6:10]$~$x[6:10]$ ( say $x=x_{1}=(1,2,3,4,5,6,7,8,9,10)$). What I would like to do is to do this in one step, but I am failing. I tried to regress $y$~$(x1 \leq 5))*x1+(x1 \geq6)+ (x1 \geq 6)*x1 $ and I kind of see why, since for $x1 \geq 6$,I have to deal with two intercepts. Any way of doing this? Thanks
-
$\begingroup$ There are a number of posts on this site about this. The magic phrase you need is either "breakpoint" or "broken stick". I will not give a link to a specific one as which one is relevant to you may depend on other details of you real model. $\endgroup$ – mdewey Oct 16 '16 at 15:43
-
1$\begingroup$ A request for R code is likely off topic, but the more general question is not. Do you want it continuous at breakpoints or discontinuous at breakpoints? $\endgroup$ – Glen_b Oct 16 '16 at 23:59
The model should look something like this:
$$ E[Y|X] = \beta_0 + \beta_1 I(X\ge6) + \beta_2X + \beta_3I(X\ge6)X $$
In this case your model for $X<6$ will be:
$$ E[Y|X] = \beta_0 + \beta_2X $$
and for $X\ge6$ it will be:
$$ E[Y|X] = (\beta_0 + \beta_1) + (\beta_2 + \beta_3)X $$
-
1$\begingroup$ Also worth mentioning is that you can test if $\beta_1=0$ and $\beta_3=0$ to determine if there are significant differences between the first five observations and the last 5. $\endgroup$ – dlnB Mar 15 '19 at 22:10