# [R] Piecewise nls w/ boundary as a fitting parameter

Primoz PETERLIN primozz.peterlin at gmail.com
Wed May 19 14:19:07 CEST 2010

```Hello,

Fitting a piecewise smooth curve to a set of points (and a piecewise
linear function in particular) seems to be a recurring question on
this list. Nevertheless, I was not able to find an answer to a
question that bothers me.

Suppose I have the following data set, and would want to fit it with a
piecewise smooth curve, In this model data, one curve is valid for up
to 3 and another one for onwards. However, suppose I don't have this
data.

x <- 0:8
y <- c(0.5, 0.5, 0.5, 0.5, 1.914214, 2.5, 2.949490, 3.328427, 3.662278)

plot(x, y)

# Neither of these seem to work
f <- function(x, x0, y0, k) { ifelse(x < x0, y0, y0 + sqrt(k*(x-x0))) }
# f <- function(x, x0, y0, k) { (x < x0)*y0 + (x >= x0)*(y0 + sqrt(k*(x-x0))) }

fmodel <- nls(y ~ f(x, x0, y0, k), start = list(x0 = 1, y0 = 1, k = 1))

What's the proper way to deal with such a case? Am I supposed to
somehow obtain the break point separately, and then fit only y0 and k?
What is the preferred method for obtaining break point (I am not even
sure if I am using this term correctly).