An R script to run Sweave and create the PDF

I usually create my R scripts inside a .Rnw files that I run with cacheSweave and the I convert to PDF. Since I started the PhD I am creating a lot of this files so I developed a script to run the .Rnw files and to create the corresponding .pdf file in a single command without needing to open R and run the source.

The script is the following:

# Get the arguments from the Rscript
args <- commandArgs( trailingOnly = TRUE )

# Get the sweave (original) and the tex (created with sweave) files
sweave_file <- args[ 1 ]
file_name   <- strsplit( sweave_file, "[/]" )[[ 1 ]]
tex_file    <- paste0( getwd(), "/", strsplit( file_name[ length( file_name ) ], "[.]")[[ 1 ]][ 1 ], ".tex" )

# Load cacheSweave and run the sweave file
library( cacheSweave )
Sweave( sweave_file, driver = cacheSweaveDriver)

# Convert the tex file to pdf
system( paste0( "pdflatex ", tex_file ) )
system("rm *.aux *.log *.out *.toc")

And I run it as:

Rscript ../../scripts/creaPdf.R ../../scripts/mosaicism_analysis.Rnw

The file ../../scripts/creaPdf.R is the one containing the code above. The file ../../scripts/mosaicism_analysis.Rnw is the one that will be executed (and this execution will create a .tex file) and converted to PDF.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: