问题
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?
回答1:
If you are looking for adding sigma, a, b, c as new columns in your original dataset, you can do the following:
DT[, c("sigma", "a", "b", "c") := {
c.0 <- min(y) * 0.5
model.0 <- lm(log(y - c.0) ~ x, data=.SD)
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=.SD,
start=start,
control=nls.control(maxiter=500))
c(.(sigma=summary(model)$sigma), as.list(coef(model)))
},
by=.(groups)]
output:
x y groups sigma a b c
1: 1 15.4 1 0.2986243 0.5265405 0.4565363 14.56728
2: 2 16.0 1 0.2986243 0.5265405 0.4565363 14.56728
3: 3 16.4 1 0.2986243 0.5265405 0.4565363 14.56728
4: 4 17.7 1 0.2986243 0.5265405 0.4565363 14.56728
5: 5 20.0 1 0.2986243 0.5265405 0.4565363 14.56728
6: 6 23.0 1 0.2986243 0.5265405 0.4565363 14.56728
7: 7 27.0 1 0.2986243 0.5265405 0.4565363 14.56728
8: 8 35.0 1 0.2986243 0.5265405 0.4565363 14.56728
9: 1 25.4 2 0.2986243 0.5265404 0.4565363 24.56728
10: 2 26.0 2 0.2986243 0.5265404 0.4565363 24.56728
11: 3 26.4 2 0.2986243 0.5265404 0.4565363 24.56728
12: 4 27.7 2 0.2986243 0.5265404 0.4565363 24.56728
13: 5 30.0 2 0.2986243 0.5265404 0.4565363 24.56728
14: 6 33.0 2 0.2986243 0.5265404 0.4565363 24.56728
15: 7 37.0 2 0.2986243 0.5265404 0.4565363 24.56728
16: 8 45.0 2 0.2986243 0.5265404 0.4565363 24.56728
来源:https://stackoverflow.com/questions/52507407/exponential-curve-fitting-with-nls-using-data-table-groups