I've 10 predictors and 1 response variable. I tried running linear model using

lm(y~., data=mydata)

If I just need to remove one predictor 'age', I can write

lm(y~.-age, data=mydata)

If the summary of the model suggest that more than one variables are not significantly contributing to the model. How can I efficiently write a code for linear model removing these variables.

I tried

lm(y.-c(age, weight), data=mydata)

But I got the error

Error in model.frame.default(formula = y ~ . - c(age, weight),  : 
variable lengths differ (found for 'c(age, weight)')

Please help.

  • $\begingroup$ Software-related questions are off-topic on this site so I'm voting to close this thread. As a hint, you can always use lm(mpg~.-cyl-disp-hp, mtcars) or lm(mpg~., mtcars[,-c(5:10)]). $\endgroup$ – Tim Feb 18 '16 at 9:39
  • $\begingroup$ No problem :) You can always take a tour stats.stackexchange.com/tour to learn more about the site ;) $\endgroup$ – Tim Feb 18 '16 at 9:45

You can chain several predictors with a minus sign

lm(y ~ . - age - weight, data=mydata)
  • $\begingroup$ Thanks. I should have tried it before asking. I was trying to use a vector of variables instead. $\endgroup$ – Dr Nisha Arora Feb 18 '16 at 9:42

Following are some of the methods which can be used :

  1. Subset selection : Identifies subset of predictors that are related to the response. This can be accomplished using best subset selection or stepwise subset selection methods.

  2. Shrinkage methods : Coefficients of predictors weakly related to response are shrunken towards zero. Ridge and Lasso regression can be used for this.

  3. Dimension reduction : Find the predictors which are linearly correlated to other predictors. Can be done using PCA (Principal component analysis).

For more details and worked out examples in R you can refer to chapter 6 from "Introduction to Statistical Learning", which can be downloaded for free from here -> http://www-bcf.usc.edu/~gareth/ISL/

  • $\begingroup$ I am already following the same book. And recently read about these methods. But here I am concerned about how to write a code for removing selected variables from the model. $\endgroup$ – Dr Nisha Arora Feb 18 '16 at 9:39

Not the answer you're looking for? Browse other questions tagged or ask your own question.