R sink: Output with time

1.6k views Asked by At

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.

2

There are 2 answers

2
Greg Snow On

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 
> 
1
CephBirk On

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()