Python in Sweave document

February 9, 2010

(This article was first published on » R, and kindly contributed to R-bloggers)

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}") )
        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.

To leave a comment for the author, please follow the link and comment on their blog: » R. offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Tags: , , ,

Comments are closed.


Mango solutions

RStudio homepage

Zero Inflated Models and Generalized Linear Mixed Models with R

Quantide: statistical consulting and training



CRC R books series

Contact us if you wish to help support R-bloggers, and place your banner here.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)