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 the formula, but not how to get eg. y ~ 10 + 1.25b as opposed to y~b or a table of what intercept, b etc. equal
This is the code I'm working with currently:
a = c(1, 2, 5)
b = c(12, 15, 20)
model = lm(a~b)
summary(model)
formula = formula(model)
formula
coefficients(model)
What I'd like to get from the above is y ~ -5.326 + .51b
Thanks
Edit: In my actual code I'm working with over 63 predictors and 18 different models, so I'd like something that can scale up without too much work.
Might I suggest an edit to lukeA's excellent answer:
This will make sure that negative coefficients are printed correctly
Suppose you land up with a negative coefficient for b, then the output will be
instead of
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:
These were the coefficients:
Putting it all together: