Search code examples
rcurve-fittingnls

nonlinear curve fitting in R


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.


Solution

  • 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