Emeline
Emeline

Reputation: 171

Multiplying results regression R

I just did a regression in R. I would like to multiply the results of each coefficient with some variables. How can I do it?

Coefficients:
                                Estimate Std. Error t value Pr(>|t|)   
(Intercept)                    1.210e+00  7.715e-01   1.568  0.13108   
SDCHRO_I                      -1.846e-01  2.112e-01  -0.874  0.39157   
functional_cognitive_level3    4.941e-02  7.599e-02   0.650  0.52224     
rev_per_members               -4.955e-06  5.827e-06  -0.850  0.40432   

And I want something like this:

1.210e+00 + -1.846e-01 * var1 + 4.941e-02 * var2 +   4.941e-02 * var3 

Is there a way to do it?

Upvotes: 1

Views: 1459

Answers (2)

Edward
Edward

Reputation: 18728

You can use model.matrix.

data(mtcars)

lm1 <- lm(mpg~cyl+disp+hp, data=mtcars)

res <- coef(lm1) %*% t(model.matrix(lm1))
all(res==predict(lm1))
#[1] TRUE

Upvotes: 3

mhovd
mhovd

Reputation: 4067

You can access the coefficients with model$coefficients. For example, if you want to multiply all coefficients with 10, you can do

df = data.frame(x = runif(100), y = runif(100), z = runif(100))
mod = lm(formula = y ~ x*z, data = df)
mod$coefficients
#> (Intercept)           x           z         x:z 
#>   0.6449097  -0.1989884  -0.3962655   0.4621273
mod$coefficients*10
#> (Intercept)           x           z         x:z 
#>    6.449097   -1.989884   -3.962655    4.621273

Created on 2020-07-10 by the reprex package (v0.3.0)

However, if you want to do like in your example, you need to access the invididual coefficients with model$coefficients[i], e.g.

df = data.frame(x = runif(100), y = runif(100), z = runif(100))
mod = lm(formula = y ~ x*z, data = df)

mod$coefficients[1]*10
#> (Intercept) 
#>    5.994662
mod$coefficients[2]*10
#>         x 
#> -1.687928

Created on 2020-07-10 by the reprex package (v0.3.0)

You can even do this dynamically by looping over the length of the coefficients object.

Upvotes: 3

Related Questions