Batch Mode

R’s interactive mode is convenient for most ad hoc analyses, but typing in every command can be inconvenient for some tasks. Suppose that you wanted to do the same thing with R multiple times. (For example, you may want to load data from an experiment, transform it, generate three plots as Portable Document Format [PDF] files, and then quit.) R provides a way to run a large set of commands in sequence and save the results to a file. This is called batch mode.

One way to run R in batch mode is from the system command line (not the R console). By running R from the system command line, it’s possible to run a set of commands without starting R. This makes it easier to automate analyses, as you can change a couple of variables and rerun an analysis. For example, to load a set of commands from the file generate_graphs.R, you would use a command like this:

% R CMD BATCH generate_graphs.R

R would run the commands in the input file generate_graphs.R, generating an output file called generate_graphs.Rout with the results. You can also specify the name of the output file. For example, to put the output in a file labeled with today’s date (on a Mac or Unix system), you could use a command like this:

% R CMD BATCH generate_graphs.R generate_graphs_`date "+%y%m%d"`.log

If you’re generating graphics in batch mode, remember to specify the output device and filenames. For more information about running R from the command line, including a list of the available options, run R from the command ...

Get R in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.