26

I have a R program in a txt file say "functions.txt".
I load the "functions.txt" file the R using source("function.txt") and then call functions f1(), f2() etc. which are declared and defined within "function.txt" file.
I also need to load a couple of R libraries using library() before I can use f1(), f2() etc.

My question is can I acheive all this (i.e. calling function f1() and f2()) from the windows prompt without opening the R environment ?

So essentially I want to

  1. load the R libraries I need to run f1(), f2() etc.
  2. load the function.txt file
  3. run the individual functions f1() etc.
  4. record the result

all from from the command promt of windows c:\>

I have windows version of R installed in my computers.
It would be very kind of anyone to give a detailed answer as I am not very computer savvy.

Regards

Marek
  • 49,472
  • 15
  • 99
  • 121
babu
  • 311
  • 2
  • 4
  • 6

4 Answers4

24

Bart's post is correct, but this can be done simpler. If the code

f1 <- function() {
  print("A")
}

f2 <- function() {
  print("B")
}

f1()
f2()

is in a file 'myRcode.R'; then

Rscript myRcode.R

will load and execute it, including the two function calls.

Rscript.exe is in the same directory as R.exe -- which one may have to add to the $PATH.

Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725
9

The following "works on my machine" (not Windows though, but it should...):

If your functions.txt looks like:

f1 <- function()
{
  print("A")
}

f2 <- function()
{
  print("B")
}

the command:

Rscript -e "source('functions.txt');f1();f2()" > out.txt

should create the file out.txt containing:

[1] "A"
[1] "B"
Bart Kiers
  • 166,582
  • 36
  • 299
  • 288
  • 1
    Thanks very much for the answer. A couple of more things 1> where do I find Rscript ? when I tried in my computer I got the message --'Rscript' is not recognized as an internal or external command, operable program or batch file. and also how do i load the libraries ? – babu Apr 19 '11 at 18:26
  • Look in the installation directory of R (probably somewhere in `C:\program Files\...`). If you want to be able to run this `Rscript` executable from anywhere on your computer, you should add the directory it is in to your systems PATH variable (see: http://www.computerhope.com/issues/ch000549.htm). – Bart Kiers Apr 19 '11 at 18:41
6

Here's a command line script, based on code above:

d:\misc2\bin\Rscript.exe    d:\r_code\mycode.r

Using Windows 7, I ran it as a .bat file. Works fine. Thanks for the tip. (of course, these are just my particular subdirectories)

Frederic Close
  • 9,389
  • 6
  • 56
  • 67
Bill Yarberry
  • 101
  • 1
  • 3
0

Add the R bin directory to PATH (windows Enviromwntal variables)

  • This PC > Properties > Advanced system settings > Enviromental Variables > select Path > Edit > Add the path to R bin > save

Run command prompt, then you can use either the "R" command to start a new R session in cmd, or "Rscript" to run a script (file)