1

I am currently using sink to save my output to some text file:

sink('out.txt', append=TRUE, split=TRUE)

I would like to add to each output/message the date time at wich it was given out. sink seems not to support that. What would be the simplest way to achieve this?

That is, my expected output is

[1] "some message"

But I would like it to be

2014-12-02 13:12:12 [1] "some message"

Or something along these lines.

I prefer a solution where I do not have to adjust every single output of my script. I'd much rather just set this up in a config/include file at the start only, to keep the code clean and manageable.

FooBar
  • 15,724
  • 19
  • 82
  • 171

2 Answers2

6

Here is an approach that will print the date and time after the regular output (just before the prompt for the next command). Run the code once and it will continue doing this for the rest of the session (or until you turn it off). You could put the code into .Rprofile or a .First function and it will happen every time.

> addTaskCallback(function(expr, value, ok, visible) {
+   cat('\n',as.character(Sys.time()), '\n')
+   TRUE
+ })
1 
1 

 2014-12-04 15:02:07 
> 1 + 2
[1] 3

 2014-12-04 15:02:12 
> "some message"
[1] "some message"

 2014-12-04 15:02:18 
> 
Greg Snow
  • 48,497
  • 6
  • 83
  • 110
  • Almost perfect. It seems that clearing the workspace on Rstudio (including hidden items) does not seem to get rid of the callback. If I don't know the taskid, is restarting `R` the only way to get rid of these? (Otherwise, including this at the start of the script will keep stacking timestamps on top of each other, so I'd like to start the script with a *remove all callbacks*) – FooBar Dec 04 '14 at 22:17
  • You can just call `removeTaskCallback( getTaskCallbackNames() )` until it returns FALSE. – Greg Snow Dec 04 '14 at 22:32
1

Use paste(Sys.time(),'some message')

So in context it would be:

sink('out.txt', append=TRUE, split=TRUE)
paste(Sys.time(),'some message')
sink()
CephBirk
  • 6,422
  • 5
  • 56
  • 74
  • Check out the accepted answer on this post which may be helpful for a more permanent solution: http://stackoverflow.com/questions/1448600/change-default-prompt-and-output-line-prefix-in-r – CephBirk Dec 04 '14 at 21:51