2015-10-20 62 views
2

我正在使用以下代碼來生成包含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" 
+1

你舉的例子是不可重現。你可能是指'glm <-glm(myform,data = df)'。 – 2015-10-20 09:26:08

+0

謝謝,我改變了它。 – mql4beginner

回答

3

就個人而言,我不會,除非絕對必要使用capture.output。當你只是將打印輸出發送到文件時,如果使用data.frame或者甚至是sink,肯定有更好的選擇,如write.table。這就是說,你的代碼快速的解決將是:因爲它不是在你的例子data.frame包括我沒有使用country上述

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=dat) 
    dat$glm_predict_response <- ifelse(predict(glm,newdata=dat, type="response")>.5, 1, 0) 
    ff<-print(myform) 
    dd<-print(xtabs(~ target + glm_predict_response, data = dat)) 
    print(prop.table(xtabs(~target + glm_predict_response, data = dat), 2)) 
    e<-capture.output(ff,append = TRUE) 
    #you really don't need the second capture.output since you can 
    #just print dd to the file directly 
    capture.output(e, dd, file = "myform2.txt",append = TRUE) 
} 

注意。這在輸出文本文件:

[1] "target ~ birds" 
     glm_predict_response 
target 0 1 
    0 1 2 
    1 0 5 
[1] "target ~ birds + wolfs" 
     glm_predict_response 
target 0 1 
    0 3 0 
    1 0 5 

同樣使用sink會像(似乎更容易對我來說):

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=dat) 
    dat$glm_predict_response <- ifelse(predict(glm,newdata=dat, type="response")>.5, 1, 0) 
    dd<-xtabs(~ target + glm_predict_response, data = dat) 

    #start sinking 
    sink(file='myform2.txt', append=TRUE) 
    print(myform) 
    cat('\n\n') 
    print(dd) 
    cat('\n\n') 
    #stop sinking 
    sink() 
} 
+0

謝謝@LyzandeR給你回答和解釋.. – mql4beginner

+0

你非常歡迎@ mql4beginner。很高興我可以幫忙:) – LyzandeR