4

I want to save a part of my r script output including the commands into a text file. I know sink() but it does not include the commands or I could not find a specific option to do that.

Is there any possibility to capture the commands and its ouput within an r session. Simply write an Rmd or capture the output within the console is not the solution at the moment.

Markus Graf
  • 533
  • 3
  • 16
  • 2
    Possible duplicate of [How to write an R program that copies its source code to a file?](http://stackoverflow.com/questions/31616322/how-to-write-an-r-program-that-copies-its-source-code-to-a-file) – nicola Jan 28 '16 at 13:30
  • I don't know what you want to do with the text file, but knitr might be of interest to you. – Roland Jan 28 '16 at 13:46

2 Answers2

7

You are probably looking for the TeachingDemos package. Documentation can be found here.

Example:

library(TeachingDemos)

txtStart("test.txt")
# Your code
txtStop()

This should write both your command input and output to a file called test.txt.

Patrick Kostjens
  • 5,065
  • 6
  • 29
  • 46
  • 1
    That's almost exactly what I was looking for. Thank you. What would be nice is to include also the code comments, not just normal text comments. Is there any possibility I can extend the library with such a function? Simply overwrite the function `txtComment(...)` is leading to R2txt not found. – Markus Graf Jan 28 '16 at 14:58
  • @MarkusGraf, this does not seem to be currently possible. The `txtComment` function seems to be what you are looking for, however you should not overwrite it. Instead you should call it with the comment text as an argument. So, this would require some changes to your code, but can achieve what you want. – Patrick Kostjens Jan 28 '16 at 16:20
1

If you're working interactively, here's one idea. It was this specific problem for which I created the sinkstart() function in the rite package. Basically, this creates a pop-up tcl/tk widget that you can write commands and output to. Here's a screenshot to give you a feel:

enter image description here

There are just two relevant functions: sinkstart() starts the sink; sinkstop() turns it off. You can toggle back and forth to selectively write to the widget. Then you can just save the contents with a right-click or a key shortcut.

Thomas
  • 43,637
  • 12
  • 109
  • 140