简体   繁体   中英

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.

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM