In the future please provide your data in reproducible form so we can work with it. This time I have provided some sample data in the Note at the end.
Let kvalues
be the possible indexes of x of the change point. We do not include ones near the ends to avoid numeric problems. Then for each kvalue
we perform the regression defined in the regr
function and compute the residual sum of squares using deviance
. Take the least of thoxe and display that regression. No packages are used.
(If you want to fix the slopes then remove the slope parameters from the formula and starting values and replace them with the fixed values in the formula.)
kvalues <- 5:45
st <- list(a1 = 1, b1 = 1, a2 = 2, b2 = 2)
regr <- function(k) try(nls(y ~ ifelse(x < k, a1 + b1 * x, a2 + b2 * x), start = st))
i <- which.min(sapply(kvalues, function(k) deviance(regr(k))))
k <- kvalues[i]
k; x[k]
## [1] 26
## [1] 26
fm <- regr(k)
fm
## Nonlinear regression model
## model: y ~ ifelse(x < k, a1 + b1 * x, a2 + b2 * x)
## data: parent.frame()
## a1 b1 a2 b2
## 1.507 -1.042 1.173 -2.002
## residual sum-of-squares: 39.52
##
## Number of iterations to convergence: 1
## Achieved convergence tolerance: 2.917e-09
plot(y ~ x)
lines(fitted(fm) ~ x)
abline(v = x[k])

Note
set.seed(123)
x <- 1:50
y <- 1 - rep(1:2, each = 25) * x + rnorm(50)