# Capturing R Printed Outputs

##### Posted on December 21, 2014

I’m always surprised to find “new” (to me) functions and commands in R that I had no idea they existed. This is the case of the life-saving `capture.output()`

function.

### Motivation

I’m sure you’ve gone through this situation: you are applying some statistical tests in R, or estimating a model, and you have to use the generated results for either your report, your homework, or your thesis. In other words, your goal is to save the results that appear in your R console into a text file. How you do this without copy-pasting or taking a screenshot?

For one of my projects I was running some anova and t-test. I wanted to capture some of the results, especially the p-values. I managed to do that in a very hacky way. However, I later discovered a very short but life-saving post at Handy R things.

For illustration purposes I will use a couple of examples in the help documentation from the anova and t-test functions (for more info see `?aov`

and `?t.test`

).

Here’s the anova test example:

And here’s the t-test example:

And now the magic thanks to `capture.output()`

. In this example, I will save the test results in the file `tests.txt`

. By default this file will be created in your working directory but you can specify a different location.

This example is a little verbose so you can see what I’m doing, but you can take shorcuts and reduce the number of used commands. Note that the first use of `cat()`

is just to write a title, and indicate the file name. The rest of the commands require the argument `append = TRUE`

in order to append the new content to the specified file without overwriting the existing content.