How to run R in batch mode in Windows 7

I recently purchased The Art of R Programming with a gift card I got for Christmas. Three pages into chapter 1 it talks about running R in “batch mode”. I had never done this and thought I would give it a try. It seems very useful, especially for large programs. Here’s the example program the book provides:

pdf("xh.pdf")
hist(rnorm(100))
dev.off()

 

You type that into a text file and save it as z.R. This program produces a histogram of 100 values drawn from a standard Normal distribution and outputs the histogram to a PDF file called xh.pdf. Now we want to submit that program to R without actually opening R. That means using the command line. But first we have to update our path if we’re using Windows. The book doesn’t mention this, hence the reason for this post. Here’s how you do it if you’re running 64-bit R on Windows 7:

  1. go to Control Panel
  2. click User Accounts and Family Safety
  3. click User Accounts
  4. click “Change my environment variables” in the left menu
  5. Highlight Path and click Edit
  6. Add semicolon at the end and then add “c:\Program Files\R\R-2.15.1\bin\x64” (without the quotes; update version if different from 2.15.1).
  7. Click OK twice.
  8. Log out and log back in to have the new path settings take effect.

Now go to the command prompt. Just go to Start and type “cmd”. Next go to the directory where your R program is located. If it’s in Documents, type “cd Documents”. Finally submit the following command:

R CMD BATCH z.R

 

That runs the R program and creates a PDF file in your working directory.

3 thoughts on “How to run R in batch mode in Windows 7

  1. mlr77062

    I stumbled across this site looking for help on running R in batch mode. I have had little luck about running batch mode. Your advice on setting up the environment path was very helpful. Have to admit that using cmd line hadn’t occurred to me. Years ago I was a heavy user of SAS in batch mode. Program development was a snap. Can’t imagine using interactive for anything except trivial problems.

    Reply
  2. Paul A. Thompson

    This all works, except the command to run R interactively should be changed.

    rscript rfile.r

    Reply

Leave a Reply to mlr77062 Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.