Skip to main content
edited tags
Link
Gauthier Boaglio
  • 10.3k
  • 5
  • 52
  • 85

Switching wrintingwriting from file to stdout using "sink()" in R

Source Link
Gauthier Boaglio
  • 10.3k
  • 5
  • 52
  • 85

Switching wrinting from file to stdout using "sink()" in R

I implemented the following procedure that aims to write some files and print a message in the end of each file when the writing is done:

# Print one file per piaf
output_dir_piafs <- "OUTPUT_dataset_piafs"
unlink(output_dir_piafs, recursive = TRUE, force = TRUE)
dir.create(output_dir_piafs)
for (i in 1:length(lst_sorted)) {
    sink()      # Generates warnings...
    filename <- paste(output_dir_piafs, "/piaf_", i, ".txt", sep="")
    sink(file = filename, append = TRUE)
    sink(type = "message")
    cat("  ", colnames(file1), "\n")

    for (j in 1:length(lst_sorted[[i]])) {
        cat(j, " ")
        lapply( lst_sorted[[i]][[j]], 
                function(x) { 
                    cat(as.character(x), " ")
                }
        )
        cat("\n")
    }
        
    ## back to the console
    sink()
    cat(paste(filename, "done !\n"))
    #flush(stdout())        # Tested, no particular effect
}

My problem is that, if I do not add a sink() at the very beginning of the loop, the final writing on the standard output (cat(paste(filename, "done !\n"))) has no effect. On the other hand, adding this early sink() generates warnings that I would like to avoid:

There were 50 or more warnings (use warnings() to see the first 50)
> warnings()
Warning messages:
1: In sink() : no sink to remove
2: In sink() : no sink to remove
3: In sink() : no sink to remove

Does anyone has an idea on how sink() behaves, and/or how to get rid of those warnings?

Note: I also tried try(sink(), silent=TRUE), but the silent option prevents only from errors...