Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 707
user3051065 Avatar asked Jan 21 '14 21:01

user3051065


People also ask

How do you find the equation of a linear regression in R?

The mathematical formula of the linear regression can be written as y = b0 + b1*x + e , where: b0 and b1 are known as the regression beta coefficients or parameters: b0 is the intercept of the regression line; that is the predicted value when x = 0 . b1 is the slope of the regression line.

Which function is used for creating a regression model from given formula lm () predict () Summary ()?

Summary: R linear regression uses the lm() function to create a regression model given some formula, in the form of Y~X+X2. To look at the model, you use the summary() function.

What does lm Linearregression () do?

The lm() function is used to fit linear models to data frames in the R Language. It can be used to carry out regression, single stratum analysis of variance, and analysis of covariance to predict the value corresponding to data that is not in the data frame.

What is Pr (>| t |) in R?

The Pr(>|t|) column represents the p-value associated with the value in the t value column. If the p-value is less than a certain significance level (e.g. α = . 05) then the predictor variable is said to have a statistically significant relationship with the response variable in the model.


1 Answers

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
like image 127
lukeA Avatar answered Sep 16 '22 19:09

lukeA