#NON LINEAR REGRESSION
#data
x <- c(1,3,4,6,8,10,12,14,16,18)
y <- c(1.5,2.9,5.2,9.3,15.4,22.8,30.5,39.2,49.6,60.1)
#Fitting an exponential model and fitting the curve
MODEL <- nls(y ~ a * exp(b * x), start = list(a = 1, b = 0.2))
summary(MODEL)
##
## Formula: y ~ a * exp(b * x)
##
## Parameters:
## Estimate Std. Error t value Pr(>|t|)
## a 4.86321 0.85216 5.707 0.000451 ***
## b 0.14295 0.01109 12.886 1.24e-06 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 3.515 on 8 degrees of freedom
##
## Number of iterations to convergence: 8
## Achieved convergence tolerance: 5.064e-06
plot(x, y, main = "Exponential Fit", pch = 16)
x_pred <- seq(min(x), max(x), length.out = 100)
y_pred <- predict(MODEL, newdata = list(x = x_pred))
lines(x_pred, y_pred, col = "red", lwd = 2)
#Fitting the logistic growth model
model_logistic <- nls(y ~ a / (1 + exp(-b * (x - c))), start = list(a = 30, b = 0.2, c = 5))
summary(model_logistic)
##
## Formula: y ~ a/(1 + exp(-b * (x - c)))
##
## Parameters:
## Estimate Std. Error t value Pr(>|t|)
## a 80.1465 6.2185 12.89 3.93e-06 ***
## b 0.2567 0.0180 14.26 1.98e-06 ***
## c 13.9412 0.7066 19.73 2.15e-07 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 1.242 on 7 degrees of freedom
##
## Number of iterations to convergence: 8
## Achieved convergence tolerance: 1.549e-06
y_pred_logistic <- predict(model_logistic, newdata = list(x = x_pred))
plot(x, y, main = "Logistic Growth Model", pch = 16)
lines(x_pred, y_pred_logistic, col = "green", lwd = 2)
#Comparing the residuals and goodness of fit
res_exp <- 3.515
cat("The residual standard error value for exponential fit is:", res_exp, "and 8 degrees of freedom!\n")
## The residual standard error value for exponential fit is: 3.515 and 8 degrees of freedom!
res_log <- 1.242
cat("The residual standard error value for logistic growth model is:", res_log, "and 7 degrees of freedom!\n")
## The residual standard error value for logistic growth model is: 1.242 and 7 degrees of freedom!
cat("The good residual error value is:", min(res_exp, res_log), "\n")
## The good residual error value is: 1.242
#Predicting y values for new x values
#Now the new data set
model_log <- nls(y ~ a / (1 + exp(-b * (x - c))), start = list(a = 30, b = 0.2, c = 5))
new <- data.frame(x = c(11, 12, 13))
y_prediction <- predict(model_log, new)
print(y_prediction)
## [1] 25.62582 30.29081 35.25587