Question: Are there any packages to do piecewise linear regression, which can detect the multiple knots automatically? Thanks.
When I use the strucchange package. I could not detect the change points. I have no idea how it detects the change points. From the plots, I could see there are several points I want it could help me to pick them out. Could anyone give an example here?

Answer: 
There is a pretty nice algorithm described in [Tomé and Miranda (1984)](http://idl.ul.pt/sites/idl.ul.pt/files/docs/Tome%26Miranda2004GRL.pdf). 

> 
> The proposed methodology uses a least-squares approach to compute the best continuous set of straight lines that fit a given time series, subject to a number of constraints on the minimum distance between breakpoints and on the minimum trend change at each breakpoint.
> 
> 
> 

The code and a GUI are available in both Fortran and IDL from their website: 
<http://www.dfisica.ubi.pt/~artome/linearstep.html>
You can use the [`mcp`](https://lindeloev.github.io/mcp/index.html) package if you know the number of change points to infer. It gives you great modeling flexibility and a lot of information about the change points and regression parameters, but at the cost of speed.

The mcp website contains many applied examples, e.g.,

```r
library(mcp)

# Define the model
model = list(
  response ~ 1,  # plateau (int_1)
  ~ 0 + time,    # joined slope (time_2) at cp_1
  ~ 1 + time     # disjoined slope (int_3, time_3) at cp_2
)

# Fit it. The `ex_demo` dataset is included in mcp
fit = mcp(model, data = ex_demo)

```

Then you can visualize:

```r
plot(fit)

```

[![enter image description here](https://i.stack.imgur.com/F0FT0.png)](https://i.stack.imgur.com/F0FT0.png)

Or summarise:

```r
summary(fit)

Family: gaussian(link = 'identity')
Iterations: 9000 from 3 chains.
Segments:
  1: response ~ 1
  2: response ~ 1 ~ 0 + time
  3: response ~ 1 ~ 1 + time

Population-level parameters:
    name match  sim  mean lower  upper Rhat n.eff
    cp_1    OK 30.0 30.27 23.19 38.760    1   384
    cp_2    OK 70.0 69.78 69.27 70.238    1  5792
   int_1    OK 10.0 10.26  8.82 11.768    1  1480
   int_3    OK  0.0  0.44 -2.49  3.428    1   810
 sigma_1    OK  4.0  4.01  3.43  4.591    1  3852
  time_2    OK  0.5  0.53  0.40  0.662    1   437
  time_3    OK -0.2 -0.22 -0.38 -0.035    1   834

```

Disclaimer: I am the developer of mcp.