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

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.

Related

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.

Rscript does not recognize setGeneric function

I am trying to convert an R script into something that a client can run in batch mode. My code uses generic functions and one snippet which is near the beginning goes like:
setGeneric("testInput", function(inputData, params = list())
standardGeneric("testInput"))
I've been using R CMD BATCH and it works fine. However I couldn't find an easy way to make my script print the output on the console, so based on that (and suggestion that Rscript.exe is the "proper" way to run R batch files) I decided to switch to Rscript. However when running the very same .R file with Rscript I get the following:
Error: could not find function "setGeneric"
Execution halted
I know there is probably a trivial reason behind this but I just cannot figure it out. Can someone please point me to where the mistake is?Any suggestions?
setGeneric is part of the methods package which is usually loaded when you start R in an interactive session but not in non interactive session using Rscript or littler.
So you need to add a require(methods) before calling setGeneric in your script.
For example, this code will not work
Rscript -e "setGeneric('mean', function(x) standardGeneric('mean'))"
Error: could not find function "setGeneric"
Execution halted
But this one will work
Rscript -e "require(methods);setGeneric('mean', function(x) standardGeneric('mean'))"
Loading required package: methods
[1] "mean"

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.

Switch R script from non-interactive to interactive

I've an R script, that takes commandline arguments, where the top line is:
#!/usr/bin/Rscript --slave
I wanted to interrupt execution in a function (so I can interactively use the data variables that have been loaded by that point to work out the next bit of code I need to write). I added this inside the function in question:
browser()
but it gets ignored. A bit of searching suggests it might be because the program is running in non-interactive mode. But even more searching has not tracked down how I switch the script out non-interactive mode so that browser() will work. Something like a browser_yes_I_really_mean_it() function.
P.S. I want to avoid altering the rest of the script if at all possible. My current approach is to copy and paste the code chunks, needed to prepare the data, into an interactive session; but as the script gets more and more complex this is getting more and more unreasonable.
UPDATE: for anyone else with the same question, it appears the answer to the actual question is that it is impossible. Once you start R in a non-interactive mode the die is cast. The given answers are therefore workarounds: either you hack your code (remembering to unhack it afterwards), or you refactor to make debugging easier. (This comment is not intended as a criticism of the answers; the suggested refactoring makes the code cleaner anyway.)
Can you just fire up R and source the file instead?
R
source("script.R")
Following mdsumner's answer, I edited my script like this:
if(!exists("argv")){
argv=commandArgs(TRUE)
if(length(argv)!=4)usage_and_exit()
}else{
if(length(argv)!=4){
stop("Must set argv as a 4 element vector. E.g. argv=c(...)")
}
}
Then no other change was needed, and I was able to do:
R
> argv=c('a','b','c','d')
> source("script.R")
In addition to the previous answer, I'd create a toplevel function (e.g. doStuff) which performs the analysis you want to perform in batch. The function takes the cmd line options as input. In the batch script you source the script that contains this function and call it. In this way you can easily run the function in interactive mode and use e.g. browser().
In some cases, the suggested solution (workaround) may not work - for example, when the R code needs to be run as a part of an existing bash script. For those cases, I suggest to write in your R script into the bash script using here document:
#!/bin/bash
R --interactive << EOT
# R code starts here
argv=c('a','b','c','d')
print(interactive())
# Rest of script contents
quit("no")
# R code ends here
EOT
This way, print(interactive()) above will yield TRUE.
Sidenote: Make sure to avoid the $ character in your R code, as this would not be processed correctly - for example, retrieve a column from a data.frame() by using df[["X1"]] instead of df$X1.

Resources