Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing script as parameter to RGui

Tags:

command-line

r

I was wondering if it possible to pass parameters to RGui from command prompt in windows. I would like to do something like

RGui myScript.r param1 param2

just like I would do with RScript but I need to display a GUI.

Here is some more info regarding my needs. I want to embedd a gui written in R in my C# forms application. What would happen is I press a button in the form and the application launches a process that calls RGui with my script and some parameters. This has worked fine so far with RScript but now that I am displaying graphics I need R to be in interactive mode. Here is the code I am using:

        myProcess.StartInfo.FileName =Pathing.GetUNCPath( r_path) + "\\Rscript";
        string script_path=Directory.GetParent(AppDomain.CurrentDomain.BaseDirectory).Parent.Parent.Parent.FullName.ToString();
        myProcess.StartInfo.Arguments = Pathing.GetUNCPath(script_path) + "\\display.r " + data_path;
        myProcess.StartInfo.UseShellExecute = true;           
        myProcess.Start();
        myProcess.WaitForExit();
like image 382
Bogdan_s02 Avatar asked Aug 04 '11 16:08

Bogdan_s02


1 Answers

As said, you normally cannot do that. If you hack into your Rprofile or Rprofile.site ( see ?Startup for more information, or this site), you can go around that, but the code is not portable to other computers. So if you feel really lucky and daring, you can try to do the following.

You add this code to your Rprofile file or Rprofile.site (which can be found in the /etc folder of your R install):

Args <- commandArgs(trailingOnly=TRUE)
if(length(Args)>0 & sum(grepl(" -f ",commandArgs()))==0 ){          
    if(grepl("(?i).r$",Args[1])){
        File <- Args[1]
        Args <- Args[-1]
        tryCatch(source(File) , error=function(e) print(e) )
    }
}

This will allow you to do :

Rgui --args myscript.r arg1 arg2
Rscript myscript.r arg1 arg2
R --args myscript.r arg1 arg2
R -f myscript.r --args arg1 arg2

The --args argument will take care of the popups that @iterator warns for. The code will result in a variable Args which is contained in the base environment (which is not .GlobalEnv!). This variable contains all arguments apart from the filename. You can subsequently access that one from your script, eg:

#dumb script
print(Args)

If called with Rgui or R, there will also be a variable File that contains the name of the file that has been sourced.

Be reminded that changing your rProfile is not portable to other computers. So this is for personal use only. You can also not give -f as a parameter after --args, or you'll get errors.

Edit: We better search for " -f " than "-f" as this can occur in "path/to/new-files/".

like image 121
Joris Meys Avatar answered Oct 17 '22 06:10

Joris Meys