Detecting straight line segment in a series I would like to detect "last" straight line portion in a plot in "R". For example,in the image below, that section would be the one shown under the Red bubble.

What package or method should I use to first identify that section and then get slope and intercept of the line segment. 
 A: Just a few thoughts, open for any suggestions: 


*

*As you know the linear part to always occur at the end, I would naturally start any analysis at the end of the series. 

*If there is very little noise in your series at all, you might be able to use a very simplistic approach altogether: take the derivative of your series, then use it to search back to front for the first big change in derivative values. This should happen about at the start of your linear part of the series. Determining the linear fit parameters could then be done using standard techniques. 

*A similar approach would be to use the last $n$ values of your series to fit a linear model and remember the error (e.g. RMSE). With repeating this process while increasing $n$ (e.g., quadratically), you could see when the error starts rising. This is going to happen as you reach/overstep the linear part towards the beginning of the series. 
  n     error
  4      0.01
  8      0.02
 16      0.02
 32      0.01
 64      0.08 <-- start of divergence? 
128       0.2
256       0.3

Having found this point, fitting a linear model to all points from there to the end of the series should do the trick. BTW: a similar effect might be visible when monitoring the slope and intercept of the linear model, as the first models will have very similar parameters (could be that you have to normalize them prior to comparison, depending on the implementation you use). But my guess is that the model will of course try to fit the majority of data, so looking at the RMSE might be the better idea.
A: I did a bit more research and found two packages in R that could work in my scenario.


*

*Segmented

*Strcchange


Eventually I used segmented as below:
  plot(x,y)
  lin.mod <- lm(y~x)
  m <- mean(x)
  segmented.mod <- segmented(lin.mod, seg.Z = ~x, psi= m)
  sl <- slope(segmented.mod)
  inter <- intercept(segmented.mod)

Thank you for your comments! 
