[R] Opening a script with the R editor via file association (on Windows)

Christopher Green cggreen at stat.washington.edu
Tue Aug 7 00:13:47 CEST 2007


On Fri, 3 Aug 2007, Duncan Murdoch wrote:

> On 03/08/2007 7:16 PM, Christopher Green wrote:
>> Is there an easy way to open an R script file in the R Editor found in
>> more recent versions of R on Windows via a file association? I am looking
>> for functionality akin to how the ".ssc" file extension works for S-Plus:
>> upon double-clicking on a ".R" file, Rgui.exe starts up and loads the 
>> script file in the R Editor.
>> 
>> As far as I can tell, Rgui.exe does not have a command line option to load
>> a file (so associating ".R" with "Rgui.exe %1" won't work). I can get 
>> Windows
>> to start Rgui.exe when I double-click on a script file, but that's about 
>> it.
>> I also don't see any way to have Rgui.exe evaluate an expression provided 
>> on
>> the command line (which would allow "file.edit(%1)"). I also thought about
>> creating a custom .First calling 'file.edit' in a batch file, but then I'd 
>> have
>> to start R, load the .First file, then quit and restart R, so that's out.
>> 
>> Is there an easy way to do this without resorting to some other R GUI?
>
> Easy?  Not sure.  But the following works:
>
> Set up the association as
>
> "F:\R\R-2.5.1\bin\Rgui.exe" --args "%1"
>
> (with obvious modifications to the path) and put this line in your 
> RHOME/etc/Rprofile.site file:
>
> utils::file.edit(commandArgs(TRUE))
>
> You could make things more sophisticated if you don't want a blank edit 
> window to open in case you're not using this shortcut.
>
> Duncan Murdoch
>

Thanks to Duncan for pointing me towards commandArgs()...I was able to 
modify things so that the script editor only opens when there is a file to edit.
Essentially, there are two steps:

1. Add the line

if ( length(z <- commandArgs(TRUE)) ) utils::file.edit(z[1])

to the Rprofile.site file; and

2. Edit the registry to associate the .R extension with the command

C:\Program Files\R\R-2.5.1\bin\Rgui.exe --args "%1"

I have written up some instructions on how to do this for the faculty 
member who asked me about doing this; others may find them useful.

http://www.stat.washington.edu/software/statsoft/R/Rwinassoc.shtml

Chris Green



More information about the R-help mailing list