R 在写入文本文件和控制台(stdout)之间切换

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

我有一个 R 程序,它使用 writeLines、cat 和 print 生成大量文本,我希望能够在文本文件和控制台之间来回切换输出。一个最小的例子如下:

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

}

但这很笨拙,我有很多地方需要编辑我的写语句。有没有办法给 stdout 一个文件名,然后在文件之间切换,例如像

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

} else {
  fileConnection <- file(stdout)

}

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

提前致谢

托马斯·飞利浦

您也可以使用 stdout() 作为默认输出的连接。你可以这样做

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)
}