How to create a loop that will add new variables to a pre define glm model

[亡魂溺海] 提交于 2019-12-06 17:15:05

I would do it using update to update the formula each time in the loop:

#initiate formula
myform <- target~1
for ( i in c('birds', 'wolfs' , 'Country')) { 
    #update formula each time in the loop with the above variables
    #this line below is practically the only thing I changed
    myform <- update(myform,  as.formula(paste('~ . +', i)))
    glm<-glm(myform,data=dat)
    dat$glm_predict_response <- ifelse(predict(glm,newdata=dat,   type="response")>.5, 1, 0)
    print(myform)
    print(xtabs(~ target + glm_predict_response, data = dat))
    print(prop.table(xtabs(~target + glm_predict_response, data = dat), 2))

}

Output:

target ~ birds
      glm_predict_response
target 0 1
     0 1 2
     1 0 5
      glm_predict_response
target         0         1
     0 1.0000000 0.2857143
     1 0.0000000 0.7142857

target ~ birds + wolfs
      glm_predict_response
target 0 1
     0 3 0
     1 0 5
      glm_predict_response
target 0 1
     0 1 0
     1 0 1

target ~ birds + wolfs + Country
      glm_predict_response
target 0 1
     0 3 0
     1 0 5
      glm_predict_response
target 0 1
     0 1 0
     1 0 1

You can try something like

    list_1=list(NA)
    list_2=list(NA)
    for (i in 2 :ncol(dat)){
      dat1=dat[,1:i]
      glm<-glm(target~.,data=dat1)
      dat1$glm_predict_response <- ifelse(predict(glm,newdata=dat1,   type="response")>.5, 1, 0)

      list_1[[i-1]]=xtabs(~target + glm_predict_response, data = dat1)
      names(list_1)[i-1]=do.call(paste,as.list(colnames(dat1)[c(-1,-ncol(dat1))]))

      list_2[[i-1]]=prop.table(xtabs(~target + glm_predict_response, data = dat1), 2)
      names(list_2)[i-1]=do.call(paste,as.list(colnames(dat1)[c(-1,-ncol(dat1))]))}

But you need to have col in right order.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!