我正在使用以下代碼來生成包含glm模型的所有結果的文件。
我想保存每個模型的結果和每個模型使用的公式。
我得到的輸出有點混亂,因爲每個模型在生成的txt文件中被打印爲兩行而不是四行。如何使輸出txt文件看起來更好
我該如何解決這個問題?
玩具數據:
df <- read.table(text = "target birds wolfs
0 21 7
0 8 4
1 2 5
1 2 4
0 8 3
1 1 12
1 7 10
1 1 9 ",header = TRUE)
代碼:從txt文件
myform <-NULL
myform <- target~1
dd<-NULL
for (i in c('birds', 'wolfs')) {
myform <- update(myform, as.formula(paste('~ birds +', i)))
glm<-glm(myform,data=df)
df$glm_predict_response <- ifelse(predict(glm,newdata=df , type="response")>.5, 1, 0)
ff<-print(myform)
dd<-print(xtabs(~ target + glm_predict_response, data = df))
print(prop.table(xtabs(~target + glm_predict_response, data = df), 2))
e<-capture.output(ff,append = TRUE)
e1<-capture.output(dd,append = TRUE)
capture.output(e,e1, file = "myform2.txt",append = TRUE)
}
輸出:
[1] "target ~ birds"
[1] " glm_predict_response" "target 0 1" " 0 1 2" " 1 0 5"
[1] "target ~ birds + wolfs"
[1] " glm_predict_response" "target 0 1" " 0 3 0" " 1 0 5"
[1] "target ~ birds + Country"
[1] " glm_predict_response" "target 0 1" " 0 3 0" " 1 0 5"
你舉的例子是不可重現。你可能是指'glm <-glm(myform,data = df)'。 – 2015-10-20 09:26:08
謝謝,我改變了它。 – mql4beginner