how do i exclude specific variables from a glm in R?

52,070

In addition to using the - like in the comments

glm(Stuff ~ . - var1 - var2, data= mydata, family=binomial)

you can also subset the data frame passed in

glm(Stuff ~ ., data=mydata[ , !(names(mydata) %in% c('var1','var2'))], family=binomial)

or

glm(Stuff ~ ., data=subset(mydata, select=c( -var1, -var2 ) ), family=binomial )

(be careful with that last one, the subset function sometimes does not work well inside of other functions)

You could also use the paste function to create a string representing the formula with the terms of interest (subsetting to the group of predictors that you want), then use as.formula to convert it to a formula.

Share:
52,070

Related videos on Youtube

user3399551
Author by

user3399551

Updated on July 09, 2022

Comments

  • user3399551
    user3399551 almost 2 years

    I have 50 variables. This is how I use them all in my glm.

    var = glm(Stuff ~ ., data=mydata, family=binomial)
    

    But I want to exclude 2 of them. So how do I exclude 2 in specific? I was hoping there would be something like this:

    var = glm(Stuff ~ . # notthisstuff, data=mydata, family=binomial)
    

    thoughts?

    • rawr
      rawr about 10 years
      glm(Stuff ~ . - var1 - var2)
    • rawr
      rawr about 10 years
      also, update(var, . ~ . - var1 - var2) would work
    • user3399551
      user3399551 about 10 years
      I can only use update after i've already built my model, right?
    • G. Grothendieck
      G. Grothendieck about 10 years
      also glm(Stuff ~ ., data = subset(mydata, select = - c(var1, var2)), family = binomial)`
    • user3399551
      user3399551 about 10 years
      Thanks, G.G. Good thinking. Is there any more merit to any one of these methods? Or is this all just preference - use whatever you want?
    • rawr
      rawr about 10 years
      @user3399551 yes, you can only update an existing object