What is the word for “log” in R?

October 9, 2014 at 3:48 pm 4 comments

| Gabriel |

Like most native speakers of Stata, the most natural thing in the world is to start every script or session with a log file. Typing “log using” is like brushing your teeth, it’s the first thing you do and you just feel gross if you haven’t done it. Judging by what you get if you Google “logging in R” this seems to be something of a cultural eccentricity peculiar to Stata users as R users seems not to understand the question. In particular most responses to the question say something like “use sink(),” which ignores that to a Stata user a log file is neither the command history nor the output, but the two interpolated together so that you can see what command elicited what output.

However, much as the frustrated tourist abroad will occasionally find someone who understands what they mean in asking for a Western toilet, one great StackOverflow user speaks sufficient Stata to direct us to what we were hoping to find. Specifically, the library “TeachingDemos” includes a “txtStart()” function that behaves almost exactly like a Stata log file by default, but where you also have various options such as to suppress commands/output or to use Markdown format.

To install TeachingDemos:


Thereafter invoke it start a log file, do your work, and close it:

txtStart('mylogfile.txt') # this is similar to "log using mylogfile.txt" in Stata
#insert code here to load your data, analyze it, etc
txtStop() # this is similar to "log close" in Stata

Entry filed under: Uncategorized. Tags: .

Obfuscation Form 700 Monday Night Anomalies


  • 1. tony  |  October 9, 2014 at 4:53 pm

    If you’re willing to mess around, this is close to what R Markdown is for. You can interleave code with the output of the code, but on top of that, you can also add text commentary directly into the file.

    • 2. Fr.  |  October 13, 2014 at 4:04 am

      … and you can save plots as part of the output
      … to any desired format

      Stata is slowly catching up on that, though the results will never be as pretty as they can be in R.

  • 3. emilbebr  |  October 11, 2014 at 5:04 am

    Thank you. It would be nice if it could save the log with the timestamp as title though.

    • 4. gabrielrossman  |  October 11, 2014 at 8:08 am

      Use the Sys.time() function to get the current time. Then use paste() function to turn it into a filename. Finally, pass this object to the txtStart() function as the filename.
      This is more or less the same thing you’d have to do in Stata.
      Of course if you just want the current time to appear in the text of the log, that’s just type “Sys.time()”

The Culture Geeks

%d bloggers like this: