22

If I run R script under command line (actually I run that from calling in VBA), how can I output any error/warning messages to a txt file?

Artem Klevtsov
  • 8,896
  • 5
  • 51
  • 55
Joyce
  • 2,407
  • 7
  • 19
  • 21
  • How about yourprogram.exe > anoutputfile.txt ? Although that captures everything. On *nix you could direct stderr, not sure about Win*. See http://stackoverflow.com/questions/1109017/how-do-you-print-to-stderr-in-r – Pete855217 Jul 26 '12 at 09:20
  • 1
    You can possibly use `sink()` – Andrie Jul 26 '12 at 09:21
  • Thank you. I tried to search in web on how to use sink in R but a bit confused on how to output error/warning message in my case. Would you mind give me a quick example on how to do that? Thank you again. – Joyce Jul 26 '12 at 09:33
  • I roughly know how sink() works, but I can only output variables to the output txt file, how to output error message? – Joyce Jul 26 '12 at 09:59

2 Answers2

41

You can use sink() to divert messages as well as warnings to a file. The trick is to set the argument type="message":

Here is an example adapted from the help for ?sink:

setwd(tempdir())

## capture messages and errors to a file.
zz <- file("all.Rout", open="wt")
sink(zz, type="message")

try(log("a"))

## reset message sink and close the file connection
sink(type="message")
close(zz)

## Display the log file
readLines("all.Rout")
[1] "Error in log(\"a\") : Non-numeric argument to mathematical function"
Jthorpe
  • 8,986
  • 2
  • 44
  • 56
Andrie
  • 170,733
  • 42
  • 434
  • 486
  • 5
    However, how can I close the connection with the log file? I tried sink(), but when I want to delete the log file, I cannot delete that, as seems there is still connection. Only after I closed my R, I can delete that. How should I close the connection? – Joyce Jul 27 '12 at 02:23
  • 2
    This is because in the original answer, sink was not terminated with `type="message"` and the connection was not closed. (Fixed in the updated answer) – Jthorpe Apr 28 '17 at 18:31
21

To close the connection with the log file you have to use sink(type="message") instead of sink() and then close(zz).

Jean-François Fabre
  • 131,796
  • 23
  • 122
  • 195
André le Blond
  • 368
  • 3
  • 8