Home > Software design >  How to obtain the estimated parameters from `nls`
How to obtain the estimated parameters from `nls`

Time:08-08

I have the following data:

x <- 0:10
y <- c(1, 0.0296734797447216, -0.115268522114696, 0.0685634237231258, 
0.0462346454015914, 0.016874511238053, -0.00870738489741311, 
0.0356310001815887, 0.0558631035027085, -0.116810154142989, -0.0460902529547028)

My non-linear function is:

f <- function(t, coeff_sigma, coeff_alpha, coeff_omega) {
  coeff_sigma * exp(-coeff_alpha * t) * cos(coeff_omega * t)
}

I fitted an nls model:

fit <- nls(y ~ f(x, coeff_sigma, coeff_alpha, coeff_omega),
           start=list(coeff_sigma=2, coeff_alpha=2, coeff_omega=2),
           control = nls.control(maxiter = 1000))

The fitted model prints:

Nonlinear regression model
  model: y ~ f(x, coeff_sigma, coeff_alpha, coeff_omega)
   data: df_acf
coeff_sigma coeff_alpha coeff_omega 
     0.9996      1.0482      1.5588 
 residual sum-of-squares: 0.02705

Number of iterations to convergence: 10 
Achieved convergence tolerance: 2.309e-06

The problem:

I should use the parameter values (coeff_sigma, coeff_alpha, coeff_omega) for a later step, but the only thing I can do for now is to copy them from the screen. Is there any way to get these values from fit?

CodePudding user response:

Have you tried

result<-summary(fit)$coefficients

This returns a matrix that you can easily index and pull out the coefficients (and also std. errors and stuff if you want them)

For example:

result[,1]

returns

coeff_sigma coeff_alpha coeff_omega 
0.999570    1.048175    1.558793 

CodePudding user response:

You can do

fit$m$getPars()
#coeff_sigma coeff_alpha coeff_omega 
#   0.999570    1.048175    1.558793 

Basically, those functions in fit$m give you access to various stuff.

You can also use generic function coef, because it has an "nls" method.

coef(fit)
#coeff_sigma coeff_alpha coeff_omega 
#   0.999570    1.048175    1.558793 

The summary() is more comprehensive. But there is no need to use it unless you want standard errors, p-values, etc for the estimated coefficients.

  • Related