4554888
4554888

Reputation: 97

R: Redirecting to both stdout and a file on the fly

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!

Upvotes: 1

Views: 1281

Answers (2)

Rui Barradas
Rui Barradas

Reputation: 76450

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)

Upvotes: 1

F Trias
F Trias

Reputation: 189

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 &")

Upvotes: 0

Related Questions