Cow header

Python in Sweave document

Author: Matti Pastell
Tags: Python, Sweave, R
Feb 09 2010

Lately I have been using a lot of Python for signal processing and I quite like SciPy. However, I have been missing something like Sweave, which is great literate programming environment for R. Today I managed to look a bit more into it and found this hack on how to use Python code in Sweave document by Romain Francois. However, I wanted to be able to catch the input as well as output so I made a small changes to his Sweave Driver.

Modifications to the custom driver:

driver <- RweaveLatex() 
runcode <- driver$runcode

driver$runcode <- function(object, chunk, options){ 
  if( options$engine == "python")
    { driver$writedoc( object, c("\\\\begin{verbatim}", chunk,
    "\\\\end{verbatim}", "\\\\begin{python}", chunk,"\\\\end{python}") ) }
  else{ runcode( object, chunk, options ) 

The driver now catches the input in verbatim environment (which can be easily changed to listings) and the output to python environment. The tex document can then be processed with the python latex package to evaluate the python expressions. Tho use the driver you need to put the option “engine=”python" in your code chunks.

Example usage

My example is python code that calculates and plots the frequency response of a moving average filter. Here is the code in the Sweave document ma.Rnw. Process the file in R using the custom driver above:

Sweave( "ma.Rnw", driver = driver)

It should produce ma.tex. Then run latex (make sure you have the python package installed):

pdflatex -shell-escape ma.tex 

Which should then in turn output this ma.pdf file.

comments powered by Disqus