3

I am working on nonlinear curve fitting in R and I cannot figure out how to constrain the data using the variables... Here is an example:

dat<-read.table(text="time y
1 4.62
2 13.55
3 30.82
6 93.97
12 145.93
24 179.93", header = TRUE)
plot(data);lines(data)
model <- nls(y ~ Max * (1-exp(-k * (time - Lag))),data=dat,start=list(Max = 200, k = 0.1, Lag = 0.5))

I would like to include if (time - Lag) < 0, then y = 0 but I cannot for the life of me figure out how to do it.

  • 1
    Would doing `y ~ Max * (1-exp(-k * pmax(time - Lag)))` in your equation work? Shot in the dark. In that case, any `time - Lag < 0` would be 0, which gives you `Max * (1 - exp(0))`, or 0. –  Feb 03 '21 at 21:05

1 Answers1

4

Multiply the right hand side by (time > Lag)

st <- list(Max = 200, k = 0.1, Lag = 0.5)
model <- nls(y ~ (time > Lag) * Max * (1-exp(-k * (time - Lag))), data = dat, start = st)
model
## Nonlinear regression model
##   model: y ~ (time > Lag) * Max * (1 - exp(-k * (time - Lag)))
##    data: dat
##      Max        k      Lag 
## 185.6447   0.1523   1.6016 
##  residual sum-of-squares: 65.06
##
## Number of iterations to convergence: 4 
## Achieved convergence tolerance: 2.016e-07

plot(dat)
lines(fitted(model) ~ time, dat, col = "red")

screenshot

G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
  • just a question @G. Grothendieck, is the expression `(time > Lag)` acting as boolean (to 0 or 1)? – Manu Feb 03 '21 at 22:08
  • 1
    Yes, TRUE/FALSE will automatically be converted to 1/0 when it multiplies a number or is used in any numeric formula. – G. Grothendieck Feb 03 '21 at 22:09
  • That's interesting use of a logical condition which coerces to 0 or 1. Every day I learn something new here. Thank you @G. Grothendieck, have a great day. – Manu Feb 03 '21 at 22:40