Running R

I am assuming that you have R installed and running.

Running interactively

Just say:

  $ R

and you will be put into an R prompt. From there on, you can issue commands.

One useful command that might fit here is source("file.R") - this gets R to consume the stated file. Graphs come out fine, but textual babbling of file.R is supressed. If you want the babbling also, say source("file.R", echo=T)

If you see him saying:

[Previously saved workspace restored]

and you didn't particularly want this, say:

$ rm -rf .RData 

Running a program non-interactively

I say:

  $ cat file.R | R --vanilla | less

As usual in Unix, you can capture the output in many ways.

Running a script that makes graphs

Here is an example with a file try.R --

$ cat try.R
    z <- locator(1)

$ R --vanilla --slave < try.R

The `locator' function waits for you to either click the mouse or hit enter.

Running a script and getting .ps files

By default, when R --vanilla is run, if it encounters plots, it makes the fixed filename You can capture this file after he has finished. As an example, try:

echo 'plot(1:20, log(1:20), type="l")' | R --vanilla

After this, you will find a file sitting around. Another way is to explicitly use the postscript() command to produce .eps files or the pdf() command to produce .pdf files. Using these is not a part of "instructions for running R". :-)

Parsing commandline arguments

Here is a file try.R:

D = read.table(commandArgs()[4], col.names=c("x"))

I can run it with many different data files like this:

cat try.R | R --slave --args > 1.rout
cat try.R | R --slave --args > 2.rout
cat try.R | R --slave --args > 3.rout

What is going on is like this. The function commandArgs() returns the commandline arguments, starting from index 1. All the tokens on the commandline are shown to you. So if you had said "R --slave" then the element 1 would be "R", element 2 would be "--slave" and element 3 would be "". This can be done and it works.

The trouble is that R complains about not being a recognised argument. To soothe his nerves, we say --args. But that shows up as the 3rd argument. So becomes the 4th argument. To read in the file I feed the filename commandArgs()[4] to read.table.

I do the following in a Makefile:

Rres : 1.rout 2.rout 3.rout

%.rout :
        cat myfile.R | R --slave --args $< > $@

Bang syntax

If you're a Unix guy, you'll want to write executables which are R programs. Here's a workaround by Peter Dalgaard to do that. Make a file testR which looks like this:

tail +3 "$0" | R --slave --args $@ ; exit $?
x <- 2+2

At the shell prompt, now:

$ chmod +x ./testR
$ ./testR 
[1] 4
[1] "x"
[1] 4
[1] "/usr/lib/R/bin/R.bin" "--slave"              "--args"              

Return to R by example

Ajay Shah
ajayshah at mayin dot org