Roelof Coertze Roelof Coertze - 6 months ago 109
R Question

Appending error messages to log file while running multiple script components in R

I am attempting to write error messages for my script to a log file. It works when I do:

test <- file("error_file.log", open = "wt")
sink(test, type = "message")
try(data <- read.delim("genes2.txt",
header = TRUE,
as.is = TRUE))
sink(type = "message", append = TRUE)
close(test)


However, when I add an additional component to the script, it does not append both error messages. In this case both input files do not exist and should give a "no such file directory" for each file. Here is my attempt for both input files:

enter code heretest <- file("error_file.log", open = "wt")

sink(test, type = "message")

try(data <- read.delim("genes2.txt",
header = TRUE,
as.is = TRUE))

sink(type = "message", append = TRUE)
close(test)

test2 <- file("error_file.log", open = "wt")
sink(test2, type = "message")

try(variables <- read.delim("Book3.txt",
header = TRUE,
as.is = TRUE,
check.names = FALSE,
text = TRUE,
na.strings = c("", NA)))

sink(type = "message", append = TRUE)
close(test2)


Thank you!

P.s. would it be possible to customize my own error messages for each try()?

Answer Source

Try using this, it'll append both the messages to error_file.log:-

test <- file("error_file.log", open = "wt")
sink(test, append = TRUE, type = "message")


try(data <- read.delim("genes2.txt",
                       header = TRUE,
                       as.is = TRUE))


try(variables <- read.delim("Book3.txt",
                            header = TRUE, 
                            as.is = TRUE,
                            check.names = FALSE,
                            text = TRUE,
                            na.strings = c("", NA)))


sink(type = "message")

So, error file would have:-

Error in file(file, "rt") : cannot open the connection
In addition: Warning message:
In file(file, "rt") :
  cannot open file 'genes2.txt': No such file or directory
Error in file(file, "rt") : cannot open the connection
In addition: Warning message:
In file(file, "rt") :
  cannot open file 'Book3.txt': No such file or directory

I hope this solves your problem.

The trick is just open your log file and sink once in the begining. And, close sink in the end.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download