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

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.

Related

Very simple question on Console vs Script in R

I have just started to learn to code on R, so I apologize for the very simple question. I understand it is best to type your code in as a Script so you can edit and save it. However, when I try to make an object in the script section, it does not work. If I make an object in the console, R saves the object and it appears in my environment. I am typing in a very simple code to try a quick exercise on rolling dice:
die <- 1:6
But it only works in the console and not when typed as a script. Any help/explanation appreciated!
Essentially, you interact with R environment differently when running an .R script via RScript.exe or via console with R.exe, Rterm, etc. and in GUI IDEs like RGui or RStudio. (This applies to any programming language with interactive compilers not just R).
The script does save thedie object in R environment but only during the run or lifetime of that script (i.e., from beginning to end of code lines). Your code line is simply an assignment of object. You do nothing with it. Apply some function, output results, and other actions in that script to see.
On the console, the R environment persists interactively until you quit it with q(). So assigned objects remains for lifetime of your console session. After assigning, you can afterwards apply function, output results, or other actions in line by line calls.
Ultimately, scripts gathers all line by line code in advance of run for automated execution without relying on user to supply lines. Imagine running 1,000 lines of code with nested if/then or for/while loops, apply functions on console! Therefore, have all your R coding needs summarily handled in scripts.
It is always better to have the script, as you say, you can save edit correct, without having to rewrite the code to change a variable or number.
I recommend using Rstudio, it is very practical and will help you to program more efficiently and allows you to see, among other things, the different objects that you have created.

Run same R script from terminal with different arguments in parallel

I have an R script that's called the following way from the terminal:
Rscript myscript.R param1 param2
When the script finishes it generates an output .csv file that is saved somewhere on my server.
I want to be able to, by using tmux, on different panes, run the same script, just with different values for param1 param2.
How do I go about to do that? Really struggling to find the best way to do it.
So the best solution I managed to get to this problem was to basically start R sessions on each tmux window and from there just input the arguments and run the actual script.
Not the most practical but gets the job done.

How to drop into R shell after executing commands from file in R

In Python, running the interpreter with the -i flag first executes the script, then drops back into the interpreter
python -i hello.py
Hello world
>>> print("Python ftw")
Python ftw
>>>
which allows me to type commands and reach the variables after execution.
With R, this seems to be of great difficulty. I have been searching online for some time, and am surprised to see there is not so many results with the keywords "R run file shell interpreter".
With R, you can use
$ R -f myfile.R which executes and then exits the interpreter
$ Rscript myfile.R which still does the same thing.
Even worse, it does not plot when run like this and just exits without showing any signs that something has been plotted.
So, to repeat my question:
How do I make R to drop into the R shell after running commands from a file, a.k.a. a script?
Concurrently, how can I make R really plot the plots and not close them off immediately?
I can do these with Python, MATLAB, Octave, Ruby and many others, and should be able to do with R too.
I will answer your two questions separately:
How do I drop into a shell after my script has executed?
The function "browser" called with no arguments will allow to to drop into a shell on the line that it's called. Appending this to your script should do the trick.
How do I save graphics when not run in interactive mode?
First, check that there isn't a pdf file being created in your working directory. Depending on how you're running R, I believe it may be named "Rplots.pdf". Personally, however, I prefer to explicitly save graphics to a particular file, as such:
pdf("temp.pdf")
plot(rnorm(100))
dev.off()
which will save the plot in a new file called temp.pdf (and will overwrite any existing file by that name, so watch out).
Functions analagous to "pdf" exist for other image formats if you would prefer that.

paste single line command in R console without executing

Since I have started using R I have noticed inconsistent behaviours when pasting a complete single command line in the R GUI console. Sometimes the command is executed, sometime is not. I tried to use the "paste commands only" but the command is still executed and the option does not seem to have any effect. I want to past a complete command and not execute it.
How do I control what happens when I paste a single line?
EDIT: i think the issue is that I am also copying from notepad the "enter" character, so that's what make the command run right away. Is there a way to avoid this?
If you do not copy a newline character at the end of the command, it will not be executed when you paste it. You will need to enter one manually.
Rather than copy/paste, you might want to use an editor where you can highlight the code you want to run and then send it to the R console via a button or shortcut key. The Windows R GUI has this feature, as does Rstudio.

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