Can I declare file for output to console? - r

I have a routine to write (writeLines with sprintf) to output some values to the console.
I was asked to do the same output to a txt file.
What I have now is to duplicate the first set of "writeLine"s and change them to a write(..., file)
I am unable to find if I can declare a file to the console. What I am thinking is to have a function to do that and pass a parameter (file) and then just one set of statements for the write and call
diskfile <- file("results.txt", "w")
printresults("console") # This is the part I don't know how
printresults(diskfile)
If I do the printresults to the file, I can read from it and present to the console. I am using:
cat(readlines, ...)
This works fine but I preferr to have the function solution.
Is there a way to do that?
Thanks for your time,
EDIT>>> More specific
Can I do write(sprintf(...), CONSOLE)?

Would sink() (a favourite of mine) do the trick?
sink("file.txt", append = FALSE, split = TRUE)
print("Hello world")
sink()
With split = TRUE the output is passed to the console and the text file simulataneously, and the second call to sink() reverts output back to the console.
Both the console and file.txt print
"Hello world"

Related

Printing check mark is triggering warning when running R cmd checks

I‘m writing a simple function that reads multiple files from the user, then it prints into the terminal (print) file name and yes or no next to it, if it was valid/invalid. I would like to use x/✓symbols.
The problem however, since the check symbol is not in ascii, R cmd is throwing a warning. I tried several approaches (charToRaw, intToUtf8, symbol(“\326”) yet non is working with simple print in terminal.
As an example:
Df <- data.frame(file = myfiles, status = “x”)
Df$status[1]= “✓”
print (Df)
Any idea? Thanks
The cli package offers a way to print these with cli_alert_success and cli_alert_danger. Presumably, you have some more complicated check as to if the file was valid. Store that as a boolean instead of the explicit character.
Df <- data.frame(file = myfiles, isValid = myValidityCheckFx(myfiles))
purrr::walk2(
Df$file, Df$isValid,
~if(.y) cli::cli_alert_success(.x) else cli::cli_alert_danger(.x)
)

sink vs console output---what is the opposite of message()?

I am trying to take full control of output to both the console and the (split) sink file. For one, I want certain output to be colored on the [ansi] console but not clutter up my Rout file.
I know of two basic commands:
cat() outputs to both the console and the sink file.
message() outputs only to the console (via file stderr), but not to the sink file.
I start with
messageln <- function(...) {
boldblue <- "\033[34;1m"; ansioff <- "\033[0m"
if (interactive()) message(boldblue) # fails. stderr dest overrides
cat(..., sep="")
if (interactive()) message(ansioff) # fails. stderr dest overrides
}
Problem 1: the ansi terminal command is emitted and interpreted by my console only if I use cat instead of message. this is presumably because message emits its own ansi-off to turn off coloring.
Problem 2: is there an opposite to message() that outputs a string only to the sink file but not to the console?

R sink() message and output to same file - sanity check

I'm using R's sink() function to capture errors, warnings, messages and console output into a single text file.
I'm wondering if simultaneously sinking both message and output types to a single open file is bad to do?
I capture all of the above into a single file, but I must open a file handle to allow both sink types to be captured. The following code illustrates using the file handle approach:
message_filename = 'script_messages.txt'
try(message_file <- file(message_filename, open="at")) # open file for appending in text mode
sink(message_file, type="message")
sink(message_file, type="output")
cat("\n\n")
message(format(Sys.time(), "%a %b %d %Y %X TZ(%z)"), appendLF = TRUE)
# next line produces messages since file doesn't exist
try(source("import_file.R"), silent = TRUE)
# Save and close writing errors, warnings, messages, and console output to a file
sink(type="output")
sink(type="message")
close(message_file)
If I don't open a file handle, then the sink 'output' type messages are the only ones captured in the text file.
The documentation on sink {base} has some key info in the first half of the Details section, but I'm not fluent enough to be sure I've implemented it properly.
I believe it's to do with the global option for warn. The default is warn=0 which means "warnings are stored until the top–level function returns". In other words, when you source("script.R"), R stores up the warnings and prints them once your script has finished, i.e. after you've run sink(type="output"); sink(type="message"); close(message_file).
To change this you can call options(warn=1) before you source your script, this will print warnings as they occur and will therefore be caught by your sink. This only needs to be run once per session.

Error Handling and logging in R

I have written a function in R to print any message both to log file and console. But if there is any unexpected error while running the code, then error is displayed only to console. Is there any way to write error message to both console and log file? Here is the function..
log_con <- file("Text1.txt", open="a")
loggerfn<-function(Message,LogConnection=log_con){
cat(Message, file = LogConnection)
cat(Message)
}
Here is the sample code to...
for (i in 1:10)
{
loggerfn("loop begins\n",log_con)
a <- rnorm(n = 100, mean = i, sd = 5)
loggerfn(mean(a),log_con)
loggerfn("loop Completed\n",log_con)
if(i==8){
sdfs
}
}
In above code I have intentionally introduced error by providing undefined object sdfd.Below provided Error message is shown only in console, is there any way to write error message to both console and logfile?
Error: object 'sdfs' not found
use sink() to divert messages as well as warnings to a file. The trick is to set the argument type="message"
refer http://www.statmethods.net/interface/io.html
and Output error/warning log (txt file) when running R script under command line
https://stat.ethz.ch/R-manual/R-devel/library/base/html/sink.html
The sink( ) function defines the direction of the output.
Description
sink diverts R output to a connection (and stops such diversions).
sink.number()
reports how many diversions are in use.
sink.number(type = "message") reports the number of the connection currently being used for error messages.
Usage
sink(file = NULL, append = FALSE, type = c("output", "message"),
split = FALSE)
sink.number(type = c("output", "message"))
direct output to a file
sink("myfile", append=FALSE, split=FALSE)
return output to the terminal
sink()
The append option controls whether output overwrites or adds to a file. The split option determines if output is also sent to the screen as well as the output file.
Here are some examples of the sink() function.
output directed to output.txt in c:\projects directory.
output overwrites existing file. no output to terminal.
sink("c:/projects/output.txt")
output directed to myfile.txt in cwd. output is appended
to existing file. output also send to terminal.
sink("myfile.txt", append=TRUE, split=TRUE)
When redirecting output, use the cat( ) function to annotate the output.

R write(append=TRUE) overwrites file contents

Here's my R code:
out = file('testfile')
write('hello', file=out, append=T)
write('world', file=out, append=T)
close(out)
When I run this (using R 3.1.0), testfile then contains:
world
I expected:
hello
world
The same behavior happens if I use cat() instead of write(). Why? How can I append to files?
You must open the file for writing:
out = file('testfile', 'w')
...
When R opens (or does not open) connections automatically is a bit complicated, but it's explained in the help (?file).
If you do not pass 'w', each write call opens and closes the file, and I guess this causes the strange behaviour you observe.
If you want to open an existing file for appending, use
out = file('testfile', 'a')
The clue comes in the help page for cat (which write is a wrapper for):
append logical. Only used if the argument file is the name of file
(and not a connection or "|cmd"). If TRUE output will be appended to
file; otherwise, it will overwrite the contents of file.
When using connections you should set the connection to be opened for appending, eg:
file('testfile', open="a")

Resources