R switch between writing to a text file and the console (stdout)

Viewed 56

I have an R program that generates a lot of text using writeLines, cat and print, and I would like to be able to switch the output back and forth between a text file and the console. A minimal example follows:

WRITE_TO_TEXT_FILE <- TRUE
TEXT_FN <- "C:/temp/test.text"

if (WRITE_TO_TEXT_FILE) {
  fileConnection <- file(TEXT_FN )
  writeLines("My text string", fileConnection)
  close(fileConnection)

} else {
  writeLines("My text string")

}

But this is clumsy, and I have a lot of places in which I need to edit my write statements. Is there a way in which to give stdout a file name and then just switch between files, e.g. something like

if (WRITE_TO_TEXT_FILE  ) {
  fileConnection <- file(TEXT_FN )

} else {
  fileConnection <- file(stdout)

}

writeLines("My text string", fileConnection)
close(fileConnection)

Thanks in advance

Thomas Philips

1 Answers

You can also use stdout() as a connection for the default output. You can do something like

WRITE_TO_TEXT_FILE <- TRUE
TEXT_FN <- "C:/temp/test.text"

# at the start
fcon <- stdout()
if (WRITE_TO_TEXT_FILE) {
  fcon  <- file(TEXT_FN)
}


# use fcon anytime you need to write output
writeLines("My text string", fcon)


# at the very end
if (WRITE_TO_TEXT_FILE) {
  # you usually don't close stdout
  close(fcon)
}
Related