[英]How to create a loop that will add new variables to a pre define glm model
我想創建一個過程,該過程將為每個循環向一個glm模型添加一個新變量(來自變量池),該模型已經准備好包含最終模型的一部分變量了。清單中的循環結果將包含glm公式和結果。我知道如何手動執行(下面編寫了代碼),但我很高興知道如何自動執行。 這是一個玩具數據集和用於手動執行任務的相關代碼:
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
在下一個循環中,我將添加變量“ country”並執行相同的過程。在現實生活中,我有數百個變量,因此將其轉換為自動過程會很棒。
我會在循環中每次使用update
來更新公式:
#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))
}
輸出:
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
您可以嘗試類似
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))]))}
但是您需要以正確的順序排列col。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.