Python in Sweave document
Modifications to the custom driver:
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:
It should produce ma.tex. Then run latex (make sure you have the python package installed):
Which should then in turn output this ma.pdf file.
