I am assuming that you have R installed and running.
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
If you see him saying:
[Previously saved workspace restored]
and you didn't particularly want this, say:
$ rm -rf .RData
$ cat file.R | R --vanilla | less
As usual in Unix, you can capture the output in many ways.
Here is an example with a file try.R --
$ cat try.R x11(width=5,height=3.5) plot(1:10,1:10) z <- locator(1) q() $ R --vanilla --slave < try.R
The `locator' function waits for you to either click the mouse or hit enter.
By default, when R --vanilla is run, if it encounters plots, it makes the fixed filename Rplots.ps. 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 Rplots.ps 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". :-)
Here is a file try.R:
D = read.table(commandArgs(), col.names=c("x"))
I can run it with many different data files like this:
cat try.R | R --slave --args 1.data > 1.rout cat try.R | R --slave --args 2.data > 2.rout cat try.R | R --slave --args 3.data > 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 1.data" then the element 1 would be "R", element 2 would be "--slave" and element 3 would be "1.data". This can be done and it works.
The trouble is that R complains about 1.data not being a recognised argument. To soothe his nerves, we say --args. But that shows up as the 3rd argument. So 1.data becomes the 4th argument. To read in the file I feed the filename commandArgs() to read.table.
I do the following in a Makefile:
Rres : 1.rout 2.rout 3.rout %.rout : %.data cat myfile.R | R --slave --args $< > $@
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:
#!/bin/sh tail +3 "$0" | R --slave --args $@ ; exit $? x <- 2+2 x ls() print(x) commandArgs()
At the shell prompt, now:
$ chmod +x ./testR $ ./testR  4  "x"  4  "/usr/lib/R/bin/R.bin" "--slave" "--args"
Return to R by example
ajayshah at mayin dot org