# https://www.r-exercises.com/2018/06/21/non-linear-model-in-r-exercise/
d <- readr::read_csv("C:/Users/mahr/Downloads/mussel.csv")
## Parsed with column specification:
## cols(
## AREA = col_double(),
## SPECIES = col_integer(),
## INDIV = col_integer()
## )
plot(d$AREA, d$INDIV)

m <- nls(INDIV ~ a * AREA ^ b, d, start = list(a = .01, b = 1))
summary(m)
##
## Formula: INDIV ~ a * AREA^b
##
## Parameters:
## Estimate Std. Error t value Pr(>|t|)
## a 3.0582 2.9382 1.041 0.309
## b 0.5738 0.1005 5.711 8.14e-06 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 212.1 on 23 degrees of freedom
##
## Number of iterations to convergence: 20
## Achieved convergence tolerance: 2.505e-06
plot(d$AREA, fitted(m))

plot(fitted(m), resid(m), ylim = c(-1000, 1000))

m2 <- nls(INDIV ~ SSasympOff(AREA, Asym, lrc, c0), d)
summary(m2)
##
## Formula: INDIV ~ SSasympOff(AREA, Asym, lrc, c0)
##
## Parameters:
## Estimate Std. Error t value Pr(>|t|)
## Asym 1021.146 142.173 7.182 3.37e-07 ***
## lrc -9.009 0.353 -25.521 < 2e-16 ***
## c0 491.059 645.897 0.760 0.455
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 194.5 on 22 degrees of freedom
##
## Number of iterations to convergence: 0
## Achieved convergence tolerance: 1.302e-06
plot(d$AREA, fitted(m2))

plot(fitted(m2), resid(m2), ylim = c(-1000, 1000))
points(fitted(m), resid(m), col = "red")

plot(d$AREA, resid(m2))
points(d$AREA, resid(m), col = "red")

anova(m, m2)
## Analysis of Variance Table
##
## Model 1: INDIV ~ a * AREA^b
## Model 2: INDIV ~ SSasympOff(AREA, Asym, lrc, c0)
## Res.Df Res.Sum Sq Df Sum Sq F value Pr(>F)
## 1 23 1034739
## 2 22 831976 1 202764 5.3617 0.0303 *
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
AIC(m, m2)
## df AIC
## m 3 342.7165
## m2 4 339.2640