I would like to create a procedure that will add per each loop a new variable (from a pool of variables) to a glm model that allready contains few of the variables that need to be part of the final model.I than would like to have the results of the loop in a list that will contain the glm formula and results.I know how to do it manually (code is written below) but I would be happy to know how to do it automaticaly. Here is a toy dataset and the relevant code to do the task manually:
dat <- read.table(text = "target birds wolfs Country
0 21 7 a
0 8 4 b
1 2 5 c
1 2 4 a
0 8 3 a
1 1 12 a
1 7 10 b
1 1 9 c",header = TRUE)
#birds is a mandatory variable so I'll need to add one of the other variables in addition to birds
glm<-glm(target~birds,data=dat)
dat$glm_predict_response <- ifelse(predict(glm,newdata=dat, type="response")>.5, 1, 0)
xtabs(~target + glm_predict_response, data = dat)
glm_predict_response
target 0 1
0 1 2
1 0 5
glm_predict_response
prop.table(xtabs(~target + glm_predict_response, data = dat), 2)
target 0 1
0 1.0000000 0.2857143
1 0.0000000 0.7142857
#manually I would add the next variable (wolfs) to the model and look at the results:
glm<-glm(target~birds+wolfs,data=dat)
dat$glm_predict_response <- ifelse(predict(glm,newdata=dat, type="response")>.5, 1, 0)
xtabs(~target + glm_predict_response, data = dat)
glm_predict_response
target 0 1
0 3 0
1 0 5
prop.table(xtabs(~target + glm_predict_response, data = dat), 2)
glm_predict_response
target 0 1
0 1 0
1 0 1
In the next loop I would add the variable "country" and do the same procedure, In the real life I have hundreds of variables so turning it to an automatic proccess would be great.