Where can I find the logs for R executable files? - r

I have a file in R that I open with Rscript ( R for front-end windows) and it doesn't work, even if on other laptop it works. The black screen open and close in 1 second and I can't see the error.
Is there a way to find the log or smth to see why doesn't work? The file is simple, just with 3 command for install packages.
Thank you,
Edit: Here is the code. I repeat, this worked on other laptop. For sure there is an error, but because the window is close so quick, I can't see where is the problem.
install.packages("exifr",repos = "http://cran.us.r-project.org")
install.packages("dplyr",repos = "http://cran.us.r-project.org")
install.packages("rlang",repos = "http://cran.us.r-project.org")
install.packages("leaflet",repos = "http://cran.us.r-project.org")
PS: I have Strawberry installed.
edit 2: I still search for a solution. I got this message when I tried to run with Rscript:

I seems that it just opens command line console, runs the script and closes the console. This way you cannot see the output.
Simple solution (not suggested): open the script in text editor and add line Sys.sleep(60) to the end of the file which will keep the console open for extra minute.
Long-term solution: install RStudio and open the file there

Apparently you can choose a filename for R to put either it's output or it's errors into. The function
´sink` is meant to define exactly that.
Try
help(sink)
in your console to read how to put sink into your script:
sink diverts R output to a connection (and must be used again to finish such a diversion, see below!). If file is a character string, a file connection with that name will be established for the duration of the diversion. [...] Messages sent to stderr() (including those from message, warning and stop) can be diverted by sink(type = "message") (see below).
[...]
zz <- file("all.Rout", open = "wt")
sink(zz)
sink(zz, type = "message")

Related

stop() in package function doesn't end debug mode

I've created very simple package, using RStudio, to demonstrate my problems, the steps follow.
Create package with only one function
write <- function(text) {
print(text)
if (is.numeric(text))
stop("Text cannot be numeric.")
}
Build -> Install and Restart
In a new R Script, write following code
pckgname::write(1)
Result in Console:
tempPackage::write(1)
[1] 1
Error in tempPackage::write(1) : Text cannot be numeric.
Called from: tempPackage::write(1)
Browse[1]>
Problems
5a) I don't want to see "Called from: tempPackage::write(1)".
5b) More importantly, I don't want to end with "Browse[1]> " meaning debug mode is still open (also buttons like "Continue" and "Stop" are visible) so now I need to click on button "Continue" to finish debug mode to end on line with ">" but I want to end this debug mode without clicking on button "Continue" meaning when I run that one line code "tempPackage::write(1)" I want to see result in Console with finished debug mode.
Additional information:
When I use this stop in function directly in the same R Script (not called from a package), it works like I want.
Solution using following method also doesn't help with previous problems.
opt <- base::options(show.error.messages = F)
on.exit(base::options(opt))
When I found some solution e.g. on GitHub e.g. https://github.com/jakesherman/easypackages/blob/master/R/package.R and installed them and intentionally made an error then again I get what I wanted (debug mode ended and no message Called from shown).
Thank you for any help in advance.
I just did exactly as you instructed and I see the expected result:
pckgname::write(1)
[1] 1
Error in pckgname::write(1) : Text cannot be numeric.
I'm not sure what's wrong when you try it, but would recommend starting a fresh package in case something is not working correctly. You could even try reinstalling R and RStudio, as it worked first time for me and I can't think of why it wouldn't for anyone else.
For reference, here's exactly what I did:
I started the package from RStudio -> File -> New Project -> New Directory -> New Package
The only file I changed was hello.R - I added the code in your question exactly as-is.
I built the package with RStudio -> Build -> Build from source
And then installed it with install.packages("../pckgname_0.1.0.tar.gz", repos = NULL, type="source")
And loaded with library(pckgname)

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.

Why is behavior in R CMD BATCH different for options(error = utils::dump.frames)?

This is a followup to this question: R CMD BATCH or Rscript with stop on error
If in my .Rprofile I have
options(error = utils::dump.frames)
then R CMD BATCH does not stop on errors.
If I run R CMD BATCH on a file containing the following:
stop("I really mean stop!")
cat("no, I dont want this printed")
The cat command is still executed.
But when I do source on that file, R stops. Why is this true and how do I make the behavior consistent?
1. Regarding the first part of your question:
?dump.frames says:
"If dump.frames is installed as the error handler, execution will continue even in non-interactive sessions. See the examples for how to dump and then quit."
That's why R CMD BATCH does not stop on errors.
If you want to stop execution too then use (taken from the help example above!):
## A possible setting for non-interactive sessions
options(error = quote({dump.frames(to.file = TRUE); q(status = 1)}))
2. Regarding the second part of your question (code example with stop):
I suppose your dump.frames error handler is active too since to entered it into your .Rprofile and therefore the code execution continues for the reason explained above.
3 Why does R stop immediately when sourcing the same code?
Sorry, no idea (so my answer reamins incomplete for now)
4. How do I make the behavior consistent?
By using the error handler of 1.) above the code will always stop in case of an error.

Alter file.show() behaviour

I'm running file.show() in RStudio on a Mac, like this:
filename <- "/Users/me/reports/myfile.pdf" # replace with file location/name
file.show(file.path(filename), title="My File")
This does two things:
Opens my file.pdf
Opens a blank file in RStudio called "My File".
options()$pdfviewer
returns:
"/usr/bin/open"
How can I stop (2) from happening?
If you want to simply open a PDF file via RStudio on a Mac, the simplest way (as far as I know) is to use the system function:
filename <- "/Users/me/reports/myfile.pdf"
pdf <- getOption("pdfviewer") # same as options()$pdfviewer
cmd <- paste(pdf,filename)
system(cmd)
For example it is used by openPDF in Biobase (see here)
I don't know a way to alter the file.show behaviour in order to prevent a blank file being opened in RStudio. I think it has something to do with The R.app Mac OS X GUI uses its internal pager irrespective of the setting of pager. that you can see on the manual here.
Note: it is different on a Windows machine, use shell.exec(filename) directly.

Resources