Make an R script write lines to the console faster (Rgui) - r

I've written quite a large R script (1000+ lines). Currently there is a rm(list=ls()) statement at the top of the script, as I need to test how it runs cleanly.
I run the code by ctrl + A, ctrl + R
The problem is is that this seems to take a long time in the Rgui to write each line to the console before running it. I feel R should be able to write to the the console faster than this and was wondering if there is a faster way to run a script.
(ie hide the lines written to the console and just run the script)

Best way is to simply source the document. If you have it saved then just type source("FullPathOfmyfile.R") and it will run without printing the commands, it will only print the output and print statements. Alternatively you can set echo = FALSE.

Related

Is it possible to save an R script, with unique parameters used in the script, after it has run?

I'm using R for some processes, and I was wondering if it was possible to save a copy of an Rscript with the parameters in the script after it has ran - instead of args[1]. This would let the user be able to open the saved Rscript in Rstudio after the script has ran, with their argument instead of args[x] for any alterations they might want to make to plots.
For example:
Rscript plot_script.r path/to/file
read.table(args[1])
Should be:
read.table("path/to/file")
In the saved output Rscript.
Is this possible?

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.

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.

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