Denver Dang
Denver Dang

Reputation: 2615

Looping with glm function in R

So I'm just trying to do some pretty simple stuff using the glm command. I have a data frame which has 10 columns with different names and data. I then just need to do something like this:

variables <- c("reponse_var", "var1", "var2", "var3", "var4", "var5", "var6", "var7", "var8", "var9")

for (variable in variables) {
    reg <- glm(response_var ~ variable, data = df, family = binomial(link = logit))
    summary(reg)

So basically it should just use the glm function on each single variable, and then print out the output. But this just doesn't work. The output is:

variable lengths differ (found for 'variable')

I thought that since the data = df it already knows which data frame it should take the data from, and usually it is enough to just write the name of the column in the glm function. But when doing this with for loops, well, this is what I get.

Upvotes: 1

Views: 292

Answers (1)

Leevo
Leevo

Reputation: 1753

One possible solution is to pack response_var and variable into a formula() object, and then feed that into the regression. I think the error here is that you are feeding string objects into the glm().

Upvotes: 2

Related Questions