Search code examples
rlistdataframenlscoefficients

How can I get the coefficients from nlsList into a dataframe?


Is there a way to extract just the estimates from nlsList()? Sample data:

library(nlme)
dat<-read.table(text="time gluc starch solka
1 6.32 7.51 1.95
2 20.11 25.49 6.43
3 36.03 47.53 10.39
6 107.52 166.31 27.01
12 259.28 305.19 113.72
24 283.40 342.56 251.14
48 297.55 353.66 314.22", header = TRUE)
long <- tidyr::pivot_longer(dat, -1, values_to = "y")
long$name <- factor(long$name)
st0 <- list(Max = 200, k = 0.1, Lag = 0.5)
kinetics<-nlsList(y ~ (time > Lag) * Max * (1-exp(-k * (time - Lag))) | name, long, start = st0)

I would like to end up with a data frame like the image below of the samples and their estimates for Max, k, and Lag but cannot figure out how.

enter image description here


Solution

  • We could extract the coef and then loop over the 3d array with apply

    library(nlme)
    m1 <- apply(summary(kinetics)$coef, 3, function(x) x[,1])
    dat <- transform(as.data.frame(m1), name = row.names(m1))[c(4, 1:3)]
    row.names(dat) <- NULL
    

    -output

    dat
        name      Max          k      Lag
    1   gluc 299.6637 0.16155846 2.426204
    2  solka 337.5416 0.06583197 4.966971
    3 starch 353.7206 0.18416048 2.276593