How to address an Rscript parse error: premature EOF? - r

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.

Related

Trying to render R4DS to pdf

When I try to render the latest version of the book R for Data Science (R4DS), I get as far as LaTeX compilation, then am stopped by the following error message.
! Text line contains an invalid character.
l.406 #> -- ^^[
[1mAttaching packages^^[[22m --------------------------------...
Error: LaTeX failed to compile _main.tex. See https://yihui.org/tinytex/r/#debugging for debugging tips. See _main.log for more info.
>
This corresponds to the part of the R4DS book where we are shown how to load the tidyverse and, looking at the _main.tex file, I see many lines with what look like ANSI escape sequences starting on this line. They have the form ^[[1m, ^[[22m, and so on. I manually compiled the LaTeX output using lualatex and found that there are dozens if not hundreds of examples of this throughout the book. I suspected it was because I was using the colorout package in R, but it appears that that package is required, so others who are rendering successfully must be using it too. I believe I have successfully updated all relevant packages.
It looks like I "solved" the problem by changing an option in the _common.R file from crayon.enabled=TRUE to crayon.enabled=FALSE. This removed the ANSI escape sequences from the book. Previously I had tried setting options(crayon.enabled=FALSE) in my R session, but this was evidently being overridden by the setting in _common.R.
Update: 23 Nov 2022
The process for rendering the files is completely different now because of the switch to Quarto. Here's how I did it.
Rscript -e 'update.packages()'
Rscript -e 'install.packages('quarto')'
Rscript -e 'devtools::install_github("hadley/r4ds")
git clone https://github.com/hadley/r4ds.git
cd r4ds
Next, I wrote a small perl script to avoid the error messages I was getting about trying to render html material to pdf. (I'm omitting a lot of dead-ends I encountered in the process.)
#!/usr/bin/perl
use File::Slurp qw(prepend_file);
my #files = glob( '*.qmd' );
my $header = "\n---\nprefer-html: true\n---\n\n";
foreach my $file (#files) {
prepend_file($file, $header);
}
I ran the above script in the r4ds directory.
Next I loaded R and did the following:
library(quarto)
quarto_render("index.qmd", output_format = "pdf")
The above failed with the error message: "\begin{document} not found". Luckily, the aborted process leaves an index.tex file I can process and also gives a line number for the error. I went to that line number in the index.tex file and deleted the block of html I found there.
After that, I ran
lualatex index.tex
twice and got a successful render, minus the cover page. (You could presumably run xelatex index.tex instead.) There are a lot of problems with my render, such as the plots being too large to fit on the page. If I decide to spend time fixing them (unlikely, since Hadley seems to want us to use the online version) I'll modify this answer.

How do I silence this specific message written to terminal/file (when calling an 'Rscript' via a bash script)

I'm writing a bash script (to be called from the terminal -- on a Linux system) that creates a log-file prior to initiating an 'rscript' using some simple user input. I'm however running into problems in controlling what messages are included in the log file (or sent to the terminal), and can't find any solution for excluding one specific R package-load message:
Package WGCNA 1.66 loaded.
In other words I need a way to (only) silence this specific message, which is printed when the WGCNA package is successfully loaded.
I will try to keep the code non-specific to hopefully make it easier to follow.
The below block is a skeleton (excluding some irrelevant code), and will be followed by some different variants I've tried. Where, originally i tried controlling the output from the R script using sink() and suppressPackageStartupMessages(), which - I thought - should have been enough.
bash script:
#!/usr/bin/env bash
read RDS
DATE=`date +%F-%R`
LOG=~/path/log/$DATE.log
touch $LOG
export ALLOW_WGCNA_THREADS=4
Rscript ~/path/analysis.R $RDS $DATE $LOG
R script:
#!/usr/bin R
# object set-up
rds.path <- "~/path/data/"
temp.path <- "~/path/temp/"
pp.data <- readRDS(paste0(rds.path, commandArgs(T)[1]))
file.date <- paste0(commandArgs(T)[2], "_")
# set up error logging
log.file <- file(commandArgs(T)[3], open="a")
sink(log.file, append=TRUE, type="message")
sink(log.file, append=TRUE, type="output")
# main pkg call
if(suppressPackageStartupMessages(!require(thePKG))){
stop("\nPlease follow the below link to install the requested package (thePKG) with relevant dependencies\n https://link.address")
}
# thePKG method call
cat("> Running "method"\n", append=TRUE)
module <- method(thePKG_input = pp.data, ppi_network = ppi_network)
# reset sink and close file connection
sink(type="message")
sink(type="output")
close(log.file)
This doesn't output anything to the terminal (which is good), including the following in the log-file:
Package WGCNA 1.66 loaded.
> Running "method"
Error: added error to verify that it's correctly printed to the file
I want to keep my log files as clean and on point as possible (and avoid clutter in the terminal), and therefor wish to remove the package-load message. I've tried the following...
i. Omitting the sink() call from the R script, and adding
&>> $LOG
to the bash 'Rscript' call. Resulting in the same file output as above.
ii. Same as i but substituting suppressPackageStartupMessages() with suppressMessages(), which results in the same file output as above.
iii. Same as i but added
... require(thePKG, quietly=TRUE)
in the R script # main pkg call, with the same results.
These where the potential solutions I came across, and tried in different variations with no positive results.
I also wondered if the WGCNA package was loaded "outside" of the !require-loop of thePKG, since it's not affected by suppressMessages() for that call. But, introducing an intentional error (which terminated the process) prior to the if-require(thePKG)-call removed the message -- hinting at its initiation inside the loop.
I also tried calling WGCNA by itself at the start of the R script, with an added suppressMessages() to it, but that didn't work either.
The export function used in the bash script doesn't effect the outcome (to my knowledge) and removing it extends the load message to include the following (truncated to save space):
Package WGCNA 1.66 loaded.
Important note: It appears that your system supports multi-threading, but it is not enabled within WGCNA in R.
To allow multi-threading within WGCNA with all available cores, use allowWGCNAThreads() within R. Use disableWGCNAThreads() to disable threading if necessary.
(...)
I'm aware that I could send the output (only) to /dev/null, but there's other output printed to the file (e.g. > Running "method") that I still want.
Does anyone have a suggestion for how to remove this message? I'm very new to programming in R, and just started using Linux (Ubuntu LTS), so please keep that in mind when answering.
Thanks in advance.
I could gather the following execution flow from your question:
Bash_Script ----> R_Script ----> Output_to_terminal (and also a log file probably)
For the requirements stated, following commands (in bash) could help you:
grep - This command helps you search for patterns
Pipe (|) - This is an operator in Linux which helps you redirect output of one command as input to another for further processing (For eg. A | B )
tee - This command takes any input and forwards it to a file + standard output (terminal)
So, you could mix and match the above commands in your bash file to get the desired output:
You can extend
Rscript ~/path/analysis.R $RDS $DATE $LOG
with
Rscript ~/path/analysis.R "$RDS" "$DATE" "$LOG" | grep -v "Package WGCNA" | tee "output.log"
What each command does ?
a) | -> This redirects output of preceding command as input to the next. It's more of a connector
b) grep -> Normally used to search for patterns. In this example, we use it with -v option to do a invert-match instead i.e. search for everything except Package WGCNA
c) tee -> This writes output to terminal + also redirects the same to a log file name, passed as argument. You could skip this command altogether, if not needed

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.

Call SConstruct from R

How can I call a sconstruct script from R (e.g. in Rstudio)? I'd like to call SCons and, ideally, also read the output. So that I can get the print from e.g. scons --tree=all as a string.
If I run > system("scons")
I get: sh: scons: command not found
Setting the path Sys.setenv(PATH=paste(Sys.getenv("PATH"), "/path/to/my/sconstruct", sep=":")) doesn't help.
However, any other command works. E.g. if I have a Python script (in the same directory), I can call it as: > system('python test.py')
and get the expected: Hello Rld! back. >system('ls') lists the SConstruct, so I'm in the right work directory.
Calling from a Python script also works, eg: from subprocess import call call('scons') evokes the SConstruct as expected. However, calling that Python script from R -- doesn't work.
It appears as there is something in the R environment setting that I got wrong.
I'm on OS, but a portable solution would be fantastic!
You'll need to either be in the directory where the SConstruct is, specify it's file or use -C to change directory to it.
I don't know R or what the syntax is.
Sys.setenv(PATH=paste(Sys.getenv("PATH"), "/path/to/my/sconstruct", sep=":"))
Should likely be:
Sys.setenv(PATH=paste(Sys.getenv("PATH"), "/path/to/scons", sep=":"))

Is there any way in Linux to show what's going on about the freezing code on the R session?

I am running a set of selected code on R. Like
source("/tmp/r-plugin-honli/Rsource-2704-quantmod.R")
There is no output. Only the prompt '>' flickered there.
I use 'killall' to kill the R session. But I don't know where is wrong on the code. Because R did not give any output. How could I know what's going on about the code.
I'd try two things:
Run the code interactively. As in, open the Rsource-2704 file and run its lines one by one.
If that doesn't replicate the problem or is not possible, you can take Joshua Ulrich's suggestion or use:
R CMD BATCH --vanilla Rsource-2704-quantmod.R out.log
Which will run the code in a batch mode and output the usual console lines to a file called out.log (you can name it whatever you like).
Instead of using print statements, you could also take a look at the browser() command. This drops you into an interactive session at the point where the command is put. This works particularly well when trying to figure out what is happening inside a function, although I don't know if your script contains them.

Resources