1

Is there a way to redirect the R - output into a file and print it to stdout at the same time, on the fly? I want to monitor the progress and document it in a file. sink() can't do both, it seems.

Found the function tee on Unix (I use Mac and Linux) but there might be an R solution. Thanks!

4554888
  • 87
  • 1
  • 11
  • 3
    See argument `split - logical: if TRUE, output will be sent to the new sink and to the current output stream, like the Unix program tee.` – Rui Barradas Apr 16 '20 at 19:25
  • Thanks Rui, exactly what I needed ( skipped reading the documentation before searching..). – 4554888 Apr 17 '20 at 15:42
  • It works for the output, not for the error messages, but it's good: Error in sink(msg, type = "message", split = TRUE) : cannot split the message connection – 4554888 Apr 17 '20 at 15:47

2 Answers2

1

Function sink is the standard R way of redirecting output. It has an argument split that when set to TRUE will still have the output of commands print to stdout.
From the documentation, my emphasis.

split
logical: if TRUE, output will be sent to the new sink and to the current output stream, like the Unix program tee.

The following example displays this behavior.
First a data set to run a command with lots of written output.

set.seed(1234)
x <- 1:10
y <- x + rnorm(10, mean = 2, sd = 4)

These instructions are meant not to mess with my workspace. Feel free to skip them.

old_dir <- getwd()
setwd('~/tmp')

Now the split sink example.

sink(file = 'sink.txt', split = TRUE)
summary(lm(y ~ x))
sink(NULL)

summary output to both stdout and the file sink.txt.
Clean up.

unlink('sink.txt')

And back to where I was.

setwd(old_dir)
Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
0

Perhaps you can send to a sink, say outfile.txt and then start tail -f outfile.txt in another process?

sink("outfile.txt")
system("tail -f outfile.txt &")
F Trias
  • 189
  • 8