我正在使用以下代码生成一个包含glm模型所有结果的文件 我想保存每个模型的结果和每个模型使用的公式 我得到的输出有点混乱,因为每个模型在生成的txt文件中打印为两行而不是4行。
我该如何解决这个问题呢? 玩具数据:
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)
代码:
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)
}
来自txt文件的输出:
[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"
答案 0 :(得分:3)
就个人而言,除非绝对必要,否则我不会使用cacheItem
。如果您使用data.frame甚至是capture.output
,那么当您只是将打印输出发送到文件时,肯定有更好的选择,例如write.table
。也就是说,快速修复代码将是:
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)
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)
}
,因为它未包含在您的示例data.frame中。这在文本文件中输出:
country
同样使用[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