Export R output to a file

Sometimes it is useful to export the output of a long-running R command. For example, you might want to run a time consuming regression just before leaving work on Friday night, but would like to get the output saved inside your Dropbox folder to take a look at the results before going back to work on Monday.

This can be achieved very easily using capture.output() and cat() like so:

out <- capture.output(summary(my_very_time_consuming_regression))

cat("My title", out, file="summary_of_my_very_time_consuming_regression.txt", sep="\n", append=TRUE)

my_very_time_consuming_regression is an object of class lm for example. I save the output of summary(my_very_time_consuming_regression) as text using capture.output and save it in a variable called out. Finally, I save out to a file called summary_of_my_very_time_consuming_regression.txt with the first sentence being My title (you can put anything there). The file summary_of_my_very_time_consuming_regression.txt doesn’t have to already exist in your working directory. The option sep="\n" is important or else the whole output will be written in a single line. Finally, append=TRUE makes sure your file won’t be overwritten; additional output will be appended to the file, which can be nice if you want to compare different versions of your model.