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?

4
  • How about yourprogram.exe > anoutputfile.txt ? Although that captures everything. On nix you could direct stderr, not sure about Win. See stackoverflow.com/questions/1109017/… Commented Jul 26, 2012 at 9:20
  • 1
    You can possibly use sink() Commented Jul 26, 2012 at 9: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. Commented Jul 26, 2012 at 9:33
  • I roughly know how sink() works, but I can only output variables to the output txt file, how to output error message? Commented Jul 26, 2012 at 9:59

2 Answers 2

44

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"
Sign up to request clarification or add additional context in comments.

2 Comments

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?
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)
21

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.