Search code examples
rjupyter-notebookjupyter-irkernel

How to use sink() to save R output in Jupyter notebook?


Normally, I can use the sink() function to redirect R output to a file. For example:

sink("test.txt") cat("Hello World") sink()

However, in Jupyter Notebook (R kernel), using sink() did not redirect the printed output and I got nothing in the test.txt file. I know that specify filename in cat("Hello World", file = "test.txt") can save output and avoid using sink() altogether. The problem is that I have hundreds of lines written using cat() without specifying filename.

Anyone knows why sink() did not work in Jupyter? Is there other alternative way to store output printed in R?


Solution

  • You can redefine the cat function itself, if that suffices.

    f <- file("/tmp/test.txt", open = "wt")
    cat <- function(...){
        base::cat(..., file=f)
        }
    cat("Hello World\n")
    close(f)