Write R console to file with source() despite errors - r

I want to capture the input and output of R into a separate text file. I found that the best way to do so is a combination of sink() and source() commands (How to save all console output to file in R?).
My problem is that in some data constellations, I get error messages. The exeution of the script via source() seems to stop right after an error occurs. However, I would like to run the script to the end and simply record everything, including the errors.
How can I adapt my approach to "skip" errors?

You have to use tryCatch() for every error.
For example,
tryCatch({
print('This line works well');
stop('that line contains an error')
}, error = function(e){})

Related

Executing multiple source files in sequence using R

I have multiple source files in R which I want to execute daily in sequence using one cron job.
The code looks like -
Master_script.R
...
...
tryCatch({
source(abc.R)
source(pqr.R)
source(xyz.R)
}, error=function(e) {
print(e)})
...
...
In case there is an error in abc.R, an error is thrown and the rest of the Master_script.R is not executed. However, I want to execute the rest of the R files pqr.R and xyz.R incase abc.R fails.
In case there is an error in abc.R, is there a way to skip file abc.R, and continue executing the remaining source files?
FYI... I am not considering packing things up into a R package for now. Also, I don't want to create separate cron jobs.
I use tryCatch to avoid the Shinyapp crashing when encountering an error. See if this works. Good luck.
tryCatch(error = function(err) {return(error_value)},
source(abc.R)
)

How to address an Rscript parse error: premature EOF?

Running my working R script in the windows command line (cmd) using Rscript results in a parsing error (premature EOF).
When I run the script in RStudio, it compiles and runs as expected.
I have read the Rscript page in R documentation, and I see that the problem must be due to spaces in my script itself, which probably make it into the cmd console somehow during parsing, but that's as far as I get.
Or should I have done something with the #! functionality mentioned therein?
I am trying to run it on cmd:
Rscript .\start_app.r
I am in the right working directory, and have set the folder containing Rscript in my environment.
The script is too long to share, and I am too inexperienced to give you the parts that make it break (otherwise I wouldn't be here), but it is full of functions, if statements and the like, that use curly brackets and are indented. I also often include empty rows (someteimes indented) for readability. It makes use of the shiny-package. An example could be:
islocal = nchar(Sys.getenv("LOCAL"))>1 | interactive()
if (islocal){
source('../../path/app/variables/styling.R')
} else {
source('./variables/styling.R')
}
As the example above, it also includes other R code called via source()
Can that somehow make it to the cmd line and be incorrectly compiled?
I get the following messages:
Error: parse error: premature EOF
(right here) ------^
Execution halted
Not enough memory resources are available to process this command.
(I guess the second message is an unrelated issue, but include it here just to be sure.)
As suggested in a comment, the solution was changing the encoding.
As mentionned by the requestor himself, Using "Save with Encoding -> ISO-8895-1 (System default)" solves the issue.

How to make RStudio stop when meeting error or warning

When I select several lines of codes in a R script, and run it, RStudio will "smoothly" run all of the codes, even though there are some warnings and errors in the middle part. As a result, I have to carefully check the "Console" window, and to see whether there is any red lines. This is really time consuming and I may miss the errors. Are there some ways to make the running stop, when error or warning occurs?
RStudio currently works by pasting the selected text into the console. It doesn't care if there are errors in it. A better approach would be to get the text and source it.
You can get the selected text using
selected <- rstudioapi::getSourceEditorContext()$selection[[1]]$text
If you source this text instead of pasting it, it will stop at the first error. Do that using
source(exprs = parse(text = selected), echo = TRUE)
Another way to go would be to copy the text into the clipboard, then sourcing it from there. I don't think RStudio currently has a way to do that, but you can add one.
This function reads from the clipboard on Windows and MacOS; I'm not sure if pbpaste is generally available on Linux, but there should be some equivalent there:
readClipboard <- function() {
if (.Platform$OS.type == "windows")
lines <- readLines("clipboard")
else
lines <- system("pbpaste", intern=TRUE)
lines
}
This code sources the text from the clipboard:
source(exprs = parse(text = readClipboard()), echo = TRUE)
You could put either of these actions on a hot key in RStudio as an add-in. Instructions are here: https://rstudio.github.io/rstudioaddins/.
The advice above only stops on errors. If you want to also stop on warnings, use options(warn = 2) as #FransRodenburg said.
There are many ways you can force your script to stop when you encounter an error:
Save your script and run it using source(yourscript.R);
Wrap your script in a function and try and use the function;
Work in an Rmarkdown file and try and execute a chunk containing all the code you want to run (or try knitting for that matter);
If you really want to stop your script when a warning occurs, you could force warnings to be errors by using options(warn = 2) at the beginning of your script. If you just want to get rid of the red (lol), you can also suppress harmless warnings you have already checked using suppressWarnings(), or suppress all warnings for your script with options(warn = -1).
Be careful using options() outside a saved script though, lest you forget you have globally disabled warnings, or turned them into errors.
Depending on how large your script is, you may also just want to run it bit by bit using CTRL+Enter, rather than selecting lines.

Don't print the name of the directory to stdout when using here::set_here('path')

I'm using the R package 'here' to define my working directory using the following command at the start of my script:
here::set_here(path='/path/to/my_directory/', verbose = F)
Every time I run the script it prints this to the console:
here() starts at /path/to/my_directory
Is there a way to suppress this output? I tried using the invisible() function but that didn't work...
The message you’re seeing is printed when you’re attaching the ‹here› package. Simply don’t do that (it’s unnecessary anyway) to prevent it.
Otherwise, load it as follows:
suppressPackageStartupMessages(library(here))
… yeah, not exactly elegant.

Extract what was printed deep in the R console

When I execute commands in R, the output is printed in the console. After some threshold (I guess, some maximum number of lines), the R console no longer shows the first commands and their output. I cannot scroll up that far because it is simply no longer there.
How can I access this "early" output if it has disappeared from the console?
I care mostly about error messages and messages generated by my own script. I do use a script file and save my results to a file, if anyone wonders, but this still does not help solve my problem.
(I have tried saving the R workspace and R history and then loading it again, but did not know what to do next and was not able to find what I needed...)

Resources