Print or capturing multiple objects in R

2019-02-19 12:20发布

I have multiple regressions in an R script and want to append the regression summaries to a single text file output. I know I can use the following code to do this for one regression summary, but how would I do this for multiple?

rpt1 <- summary(fit)
capture.output(rpt1, file = "results.txt")

I would prefer not to have to use this multiple times in the same script (for rpt1, rpt2, etc.), and thus have separate text files for each result. I'm sure this is easy, but I'm still learning the R ropes. Any ideas?

2条回答
甜甜的少女心
2楼-- · 2019-02-19 12:36

You can store the result as a list and then use the capture.output

fit1<-lm(mpg~cyl,data=mtcars)
fit2<-lm(mpg~cyl+disp,data=mtcars)
myresult<-list(fit1,fit2)
capture.output(myresult, file = "results.txt")
查看更多
Bombasti
3楼-- · 2019-02-19 12:54

If you want multiple output sent to a file then look at the sink function, it will redirect all output to a file until you call sink again. The capture.output function actually uses sink.

You might also be interested in the txtStart function (and friends) in the TeachingDemos package which will also include the commands interspersed with the output and gives a few more options for output formatting.

Eventually you will probably want to investigate the knitr package for ways of running a set of commands in a batch and nicely capturing all the output together nicely formatted (and documented).

查看更多
登录 后发表回答