I'd like to fit exponential curves to groups 1 & 2 in the data table shown below and obtain a new column containing the residual standard error corresponding to each group. The exponential curve should follow y=a*exp(b*x)+c
## Example data table
DT <- data.table(
x = c(1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8),
y = c(15.4,16,16.4,17.7,20,23,27,35,25.4,26,26.4,27.7,30,33,37,45),
groups = c(1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2)
However, I only know how to fit nls curves and obtain the residual standard error of single groups using the code below which estimates good starting parameters a, b, and c:
subsetDT <- DT[group == 1]
c.0 <- min(subsetDT[,y]) * 0.5
model.0 <- lm(log(y- c.0) ~ x, data=subsetDT)
start <- list(a=exp(coef(model.0)[1]), b=coef(model.0)[2], c=c.0)
model <- nls(y ~ a * exp(b * x) + c,
data = subsetDT, start = start,
control = nls.control(maxiter=500))
sigma <- summary(model)$sigma
I don't want to subset DT
by group in a loop to calculate sigma
and other model information.
I know that if I was using lm
, I'd be able to do the following to obtain new columns containing model information:
DT[, `:=` (r.squared=summary(lm(log(y)~x))$r.squared,
int=coef(lm(log(y)~x))[1],
coeff=coef(lm(log(y)~x))[2]
), by=c("groups")]
How can I use :=
to fit an exponential curve and incorporate my nls parameters a, b, and c?