Python in Sweave document

[This article was first published on mpastell.com » R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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.

To leave a comment for the author, please follow the link and comment on their blog: mpastell.com » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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)