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
  • 9,193
  • 6
  • 52
  • 57
Joyce
  • 2,517
  • 8
  • 21
  • 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

42

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
  • 9,756
  • 2
  • 49
  • 64
Andrie
  • 176,377
  • 47
  • 447
  • 496
  • 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
  • 137,073
  • 23
  • 153
  • 219
André le Blond
  • 368
  • 3
  • 8