I have an lm object and want to get the formula extracted with coefficients. I know how to extract the formula without coefficients, and how to get the coefficients without
I figured out a versatile way of creating the model formula with coefficients using substitution. It's a lot more versatile than manually building a string with paste0
.
e.g.
I have a model that already has the optimized coefficients:
> model
Nonlinear regression model
model: players ~ pop * (decay^days_from_start) + ycept
data: data
pop decay ycept
6.896e+06 2.633e-01 4.300e+05
residual sum-of-squares: 1.64e+08
Number of iterations to convergence: 12
Achieved convergence tolerance: 1.49e-08
These were the coefficients:
> coef(model)
pop decay ycept
6.896421e+06 2.632545e-01 4.300453e+05
Putting it all together:
> newFormula = as.formula(substituteDirect(formula(model), as.list(coef(model))))
> newFormula
players ~ 6896421.4399627 * (0.263254460933212^days_from_start) + 430045.26142703