1

I am working with R version 3.3.1 (2016-06-21) Gui on Windows. I would like to open a file (perhaps a .txt file, perhaps a .R file, any file of the kind), that launches R and runs the code written in that file.

Is this possible? If so, how do I do it?

My goal is to have a method for my co-workers where they can double-click a file and see the results of my script after running in R. Right now they are copying all my code from a .txt file and pasting it into R.

Thanks

Simon
  • 13
  • 2
  • 1
    I guess you want a `.bat` file, see *e.g.* the answer here: https://stackoverflow.com/questions/17811871/run-r-script-from-bat-batch-file – neilfws May 25 '17 at 22:22
  • `source("your file path")` would be a little better than copy&paste. – Kota Mori May 26 '17 at 03:41

1 Answers1

1

An alternative to using a batch file is to do it entirely in a Windows shortcut. For instance, on my Windows system:

  1. Create a shortcut to c:/path/to/bin/Rscript.exe.

    For me, Windows had a "wizard" help me do this, which forced me to just identify the executable. From here, either Alt-Enter on the link or right-click and select Properties, then continue:

  2. Change "Start in" to the appropriate directory. If you are relying on specific paths for dependencies, then make sure you set this (and/or use setwd(...) within your R script).

  3. Add the filename to the command line in "Target", perhaps something like C:\R\R-3.3.3\bin\Rscript.exe myscript.R. In this example, myscript.R must exist in the directory in "Start in", though there's nothing stopping you from hard-coding the full path.

Using the link in @neilfws's comment or information here (How can I read command line parameters from an R script?, both Marek's and Dirk's answers), you can easily make it react to run-time arguments. For example, if your script includes:

opts <- commandArgs()

then opts will be a character vector with

c("C:\\R\\R-3.3.3\\bin\\x64\\Rterm.exe", "--slave", "--no-restore", "--file=myscript.R", "--args", "C:\\path\\to\\dragged_file")

and your script can "react" to the file (or directory) dragged onto the icon.

One issue with all of this is that it is entirely non-interactive. If you need popups, graphics, or other "discourse" with the user, you'll need something a little different.

r2evans
  • 141,215
  • 6
  • 77
  • 149
  • Thank you! Setting the default program that opens the .txt file to the Rscript.exe worked very well. – Simon May 29 '17 at 20:23