Rgui command-line for sourcing R file - r

What command line option to use behind Rgui.exe for immediately sourcing an R source file? Instead of having to type source("c:\MyGreatSource.R") manually afterwards. Something like:
Rgui.exe --source "c:\MyGreatSource.R"
Sounds like a simple question answered in any beginner's manual, but I couldn't find such an option anywhere.

I found a workable solution, maybe others are interested. Again, what I like to do is to start the Rgui and work there. All my work environment and functions are defined in an R source file, which I constantly develop further during working. So each of my commands in the GUI starts with Load1(); where Load1 is a function which simply sources my R file, to update the changes I have just made. Obviously, Load1 is also defined in my R file, so I need to get it in the first place, without much effort. I have set the command-line options for neither loading nor saving the workplace; I don't like my old mess from the previous session with test variables and so.
However, my solution now is to just create a workplace RData file which only contains the definition of my Load1 function. This workplace file is easily loaded at every start by just adding its path into the command-line options "D:\MyLoad1.RData"

I use a AutoHotkey Script
run,C:\Program Files\R\R-3.3.3\bin\x64\Rgui.exe
WinWait,RGui (64-bit)
WinWaitActive,RGui (64-bit)
Sleep 100
Send,source("%1%")
Send,{enter}

Related

How do I automatically have some code run everything I open up RStudio?

So for example, I want to set my global options as such:
options(stringsAsFactors = FALSE)
Sys.setenv(JAVA_HOME="C:/Program Files/Java/jre1.8.0_171")
for every RStudio session.
How can I write my code so that they are run at the beginning of each RStudio session?
Options
You can add the options script to your .Rprofile.
One of the easiest ways to access this is through the usethis library, specifically:
usethis::edit_r_profile()
The .Rproflie is always run at the start of a new session unless specifically told otherwise.
However, I only give you this with a MAJOR warning - adding code into your .Rprofile will prevent your R code from being reproducible. For this reason, I would strongly recommend you set the options call in a snippet in RStudio instead of using the .Rprofile, allowing for a keyboard shortcut to easily add to any script you run. While perhaps less convenient, I believe it's well worth the trade-off to keep your code fully reproducible. You can find more info on snippets with this support article from RStudio.
Envars
The Sys.setenv call would probably be suited well for using a .Renviron file.
Again, easily added with:
usethis::edit_r_environ()
Here is a nice reference to better explain the full use of .Rprofile and .Renviron files: https://cfss.uchicago.edu/notes/r-startup/

How to change toolkit in Octave?

My Octave crashes when I execute plot command. I found a solution in Assad Ebrahim's answer. He mentioned to switch the default toolkit to gnuplot, and change it in octave.rc file if I want to make the change permanently but I'm not clear about the permanent change in octaverc. When I open my octaverc with notepad++, it looks like this:
## System-wide startup file for Octave.
##
## This file should contain any commands that should be executed each
## time Octave starts for every user at this site.
EXEC_PATH (cstrcat (fullfile (OCTAVE_HOME, 'notepad++'), pathsep,
EXEC_PATH));
EXEC_PATH (cstrcat (fullfile (OCTAVE_HOME, 'bin'), pathsep, EXEC_PATH));
EDITOR (fullfile (OCTAVE_HOME, 'notepad++', 'notepad++.exe'));
What should I change and how?
First, the direct answer to your question is to append any command you want executed on startup to the end of the .octaverc file. So, to set a particular graphics toolkit you would add the line:
graphics_toolkit("gnuplot")
Or
graphics_toolkit("qt")
Or
graphics_toolkit("fltk")
For whichever toolkit you want.
Now, as pointed out by #Andy, if you are using Windows, it may be that you are misinterpreting a long delay for a crash. A still not entirely resolved windows bug concerns the fact that on the first plot Windows might need to create a font cache file. This can take a long time. Once this is complete, most subsequent plots will be much faster. Some info can be found about it at the following bug report page:
https://savannah.gnu.org/bugs/?45458
EDIT: in the time since this answer was posted, the bug linked above has been largely resolved. Part of the installation process now updates the font-cache file. If using a zip package rather than an executable installer, there is a batch file that should be run after extracting octave to ensure that this is done. Details are available at:
http://wiki.octave.org/Octave_for_Microsoft_Windows

Restart R within Rstudio

I'm trying to call a simple python script from within R using system2(). I've read some information I found vague that said if 'too much' memory is used, it won't work.
If I load a large dataset and use some information in it to use as arguments to pass into system2(), it will only work if I manually click "Restart R" in call Rstudio.
What I want:
df <- read.csv('some_large_file.csv')
###extracting some info called 'args_vec'
for(arg in args_vec){
system2('python', args)
}
This won't work as is. The for loop is simply passed over.
What I need:
df <- read.csv('some_large_file.csv')
###extracting some info called 'args_vec'
###something that 'restarts' R
for(arg in args_vec){
system2('python', args)
}
This answer doesn't quite get what I want. Namely, it doesn't work for me within Rstudio and it calls "system" (which presents the same problem as "system2" in this case). In fact, when I put the answer referenced above in my Rprofile.site file, it just immediately closed rstudio:
I tried the suggestion as a normal function (rather than using "makeActiveBinding", and it didn't quite work.
##restart R in r session -- doesn't work
makeActiveBinding("refresh", function() { system("R --save"); q("no") }, .GlobalEnv)
##nor did this:
refresh <- function() { system("R --save"); q("no") }
I tried a number of variations of these two options above, but this is getting long for what feels like a simple question. There's a lot I don't yet understand about the startup process and "makeActiveBinding" is a bit mysterious. Can anyone point me in the right direction?
In Rstudio, you can restart the R session by:
command/ctrl + shift + F10
You can also use:
.rs.restartR()
RStudio has this undocumented rs.restartR() which is supposed to do just that: restarting R.
However, it does not unload the packages that were loaded, nor does it clean the environment, so that I have some doubts about if it restarts R at all.
If you use RStudio, use the menu item Session > Restart R or the associated keyboard shortcut Ctrl+Shift+F10 (Windows and Linux) or Command+Shift+F10 (Mac OS). Additional keyboard shortcuts make it easy to restart development where you left off, i.e. to say “re-run all the code up to HERE”:
In an R script, use Ctrl+Alt+B (Windows and Linux) or Command+Option+B (Mac OS)
In R markdown, use Ctrl+Alt+P (Windows and Linux) or Command+Option+P (Mac OS)
If you run R from the shell, use Ctrl+D or q() to quit, then restart R.
Have you tried embedding the function call within the apply function, rather than a for loop?
I've had some pieces of code that ran the system out of memory in a for loop run perfectly with apply. It might help?
For those not limited to a command that want something that actually resets the system (no prior state, no loaded packages, no variables, etc.) you can select Terminate R from the Session menu.
It is a bit awkward (asks you if you are sure). If anyone knows something like clear all or really clear classes in MATLAB let me know!

Starting R and calling a script from a batch file

I have an R-based GUI that allows some non-technical users access to a stats model. As it stands, the users have to first load R and then type loadGui() at the command line.
While this isn't overly challenging, I don't like having to make non-technical people type anything at a command line. I had the idea of writing a .bat file (users are all running Windows, though multi-platform solutions also appreciated) that starts R GUI, then autoruns that command.
My first problem is opening RGui from the command line. While I can provide an explicit path, such as
"%ProgramW6432%\R\R-2.15.1\bin\i386\Rgui.exe"
it will need updating each time R is upgraded. It would be better to retrieve the location of RGui from the %path% environment variable, but I don't know an easy way to parse that.
The second, larger problem is how to call commands for R on startup from the command line. My first thought is that I could take a copy of ~/.Rprofile, append the extra command, and then replace the original copy of the file once R is loaded. This is awfully messy though, so I'd like an alternative.
Running R in batch mode isn't an option, firstly since I can't persuade GUIs to display themselves, and secondly because I would like the R console available, even if the users shouldn't need to use it.
If you want a toy GUI to test your ideas, try this:
loadGui <- function()
{
library(gWidgetstclck)
win <- gwindow("test")
rad <- gradio(letters[1:3], cont = win)
}
Problem 1: I simply do not ever install in the suggested default directory on Windows, but rather group R and a few related things in, say, c:/opt/ where I install R itself in, say,c:/opt/R-current so that the path c:/opt/R-current/bin will remain constant. On upgrade, I first renamed to R-previous and then install into a new R-current.
Problem 2: I think I solved that many moons ago with scripts. You can now use Rscript.exe to launch these, and there are tcltk examples for waiting for a prompt.
I have done similar a couple of times. In my cases the client was using windows so I just installed R on their computer and created a shortcut on their desktop to run R. Then I right click on the shortcut and choose properties to get the propertiest dialog. I then changed the "Start in" folder to the one where I wanted it to run from (which had the .Rdata file with the correct data and either a .First function in the .Rdata file or .Rprofile in the folder). There is also a "Run:" option that has a "Minimized" option to run the main R window minimized.
I had created the functions that I wanted to run (usually a specialized gui using tcltk) and any needed data and saved them in the .Rdata file and also either created .First or .Rprofile to run the comnand that showed the gui. The user double clicks on the icon on the desktop and up pops my GUI that they can work with while ignoring the other parts.
Take a look at the ProjectTemplate library. It does what you want to do. It loads used libraries from a batch file an run R files automatically after loading as well as a lot of other usefull stuff as well...
Using the answer from https://stackoverflow.com/a/27350487/41338 and a comment from Richie Cotton above I have arrived at the following solution to keeping a script alive until a window is closed by checking if the pointer to the window is valid.
For a RGtk2 window created and shown using:
library(RGtk2)
mainWindow <- gtkWindow("toplevel", show = TRUE)
Create a function which checks if the pointer to it exists:
isnull <- function(pointer){
a <- attributes(pointer)
attributes(pointer) <- NULL
out <- identical(pointer, new("externalptr"))
attributes(pointer) <- a
return(out)
}
and at the end of your script:
while(!isnull(mainWindow)) Sys.sleep(1)

R2PPT crashes R; are there alternatives to R2PPT?

I am attempting to automate the insertion of JPEG images into Powerpoint. I have a macro done for that already, except using R would be infinitely better for my purposes.
The package R2PPT should do this, I understand. However, I cannot use it. For example, when I try to use PPT.Open, I understand I can do it two different ways by calling method = "rcom" or method = "RDCOMClient". Using the latter, R will always crash, sending an error report to windows. Using the former, it tells me I need to install statconnDCOM , before giving the error:
Error in PPT.Open(x) : attempt to apply non-function.
I cannot install statconnDCOM freely, as I wouldn't call this work non-commercial. So if there isn't a way to get around this issue, are there at least some free alternatives to R2PPT so that I can save several hours of manual work with a simple R code? If there is a way for me to use R2PPT, that would be ideal.
Thanks!
Edit:
I'm using R version 2.15 and downloaded the most recent version of R2PPT. Powerpoint is 2007.
Do you have administrative privileges on this machine?
There is an issue with package RDCOMClient. It needs permissions to write file rdcom.err in the root of drive C:. If you don't have privileges to write to c:, there is a rather cumbersome workaround:
Close R
Create "c:\temp" folder if it doesn't exist.
Locate on your hard drive file rdcomclient.dll. It usually placed in \R\library\RDCOMClient\libs\i386\ and in \R\library\RDCOMClient\libs\x64\ (you need to patch file which corresponds your Windows version - 32 bit or 64 bit). It's recommended to make backup copy of this files before patching.
Open rdcomclient.dll in text editor (Notepad++, for example -http://notepad-plus-plus.org/)
Find in file string c:\rdcom.err - it occurs only once.
Go into overwrite mode (usually by pressing "Ins" key). It is very important that new path will have the same number of characters as original one. Type C:\temp\e.rr instead of c:\rdcom.err
Save the file.
Now all should work fine.
Arguably not an answer, but have you looked at using Sweave/knitr to render your presentations in LaTeX using something like Beamer? (As discussed on slide 17 here.)
Wouldn't help any with getting JPGs into a PowerPoint, but would certainly make putting R-output (numerical or graphical) into a presentation much easier!
Edit: if you want to use knitr (which I recommend), here's another reference.

Resources