Search code examples
rformulalinear-regression

Extract Formula From lm with Coefficients (R)


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.


Solution

  • as.formula(
      paste0("y ~ ", round(coefficients(model)[1],2), " + ", 
        paste(sprintf("%.2f * %s", 
                      coefficients(model)[-1],  
                      names(coefficients(model)[-1])), 
              collapse=" + ")
      )
    )
    # y ~ -5.33 + 0.51 * b