Zhenyu Zhang
Zhenyu Zhang

Reputation: 15

create a variable to replace variables in a model in R

When writing statistic model, I usually use a lot of co-variables to adjust the model, so I need to rewrite the variable again and again. Even though I could copy and paste, the model looks very long. Could I create a variable which could replace many variables? E.g.:

fm <- lm(y ~ a+b+c+d+e, data)

I could create a variable like: model1 = a+b+c+d+e, then the model looks like:

fm <-lm(y ~ model1, data)

I tried many ways, but it did successful, like model1 <- c(a+b+c+d),

Could someone help me with this?

Upvotes: 0

Views: 213

Answers (1)

yeedle
yeedle

Reputation: 5018

how about saving it as a formula?

model <- ~a+b+c+d

You can then extract the terms using terms, or update the formula using update

Example:

model <- mpg ~ disp + wt + cyl

lm(model, mtcars)
## Call:
## lm(formula = model, data = mtcars)
##
## Coefficients:
## (Intercept)         disp           wt          cyl  
##   41.107678     0.007473    -3.635677    -1.784944  

model <- update(model, ~. + qsec)
lm(model, mtcars)
## Call:
## lm(formula = model, data = mtcars)
##
## Coefficients:
## (Intercept)         disp           wt          cyl         qsec  
##    30.17771      0.01029     -4.55318     -1.24109      0.55277

Edit: As Kristoffer Winther Balling mentioned in the comments, a cleverer way to do this is to save the formula as a string (e.g. "mpg ~ disp + wt + cyl") and then use as.formula. You can then use familiar paste or other string manipulation functions to change the formula.

Upvotes: 2

Related Questions