#
`ifelse()`

in a Linear Model

I still don't entirely know my way around the modelling in R, so I might be approaching this in completely the wrong way. I'm trying to fit a model to some data that should initially increase linearly, then at some value, `a`

, it should flatten out. This switch should be quite sharp.

Is there a way to include an `ifelse()`

or similar statement in a formula? In my testing below I have been able to make it kind of work, but not to be able to find the point at which the value will flatten.

Should I be approaching this a completely different way? Is this a silly idea? Any help would be appreciated!

```
library(ggplot2)
dat <- data.frame(
x = c(1:10),
y = c(1:4, rep(4, 6) + rnorm(6, sd = 0.1))
)
cutoff <- function(x, a = 4) {
ifelse(x > a, a, x)
}
plt <- ggplot(dat, aes(x, y)) +
geom_point()
plt +
geom_smooth(
method = 'lm',
formula = y ~ cutoff(x),
se = FALSE
)
```

```
plt +
geom_smooth(
method = 'lm',
formula = y ~ cutoff(x, a),
se = FALSE
)
#> Warning: Computation failed in `stat_smooth()`:
#> object 'a' not found
```

^{Created on 2022-09-05 with reprex v2.0.2}