Skip to content

Instantly share code, notes, and snippets.

@cfhammill
Last active August 29, 2015 14:15
Show Gist options
  • Save cfhammill/a3aa805350d4b6c59f79 to your computer and use it in GitHub Desktop.
Save cfhammill/a3aa805350d4b6c59f79 to your computer and use it in GitHub Desktop.
This gist is an engine for Knitr to allow python code to be executed with ipython in when using Knitr and R Markdown

I'm currently translating a python statistical package to R and wanted to benchmark the packages side-by-side in an R Markdown document. So I poked around in knitr's internals to figure out how alternative code engines worked. It's pretty straight forward, just find the program you want to use, and pass it the code in your chunk. I wrote a little code snippet to do exactly that in my document (I found using stock python didn't execute my code as expected, so wanted to switch to ipython). Hopefully it may be of use to you.

In order to use the engine in an R Markdown document, download and source ipythonKnitEngine.R then include your python chunks in your document(example below).

```{r, engine = "ipython", engine.path = "path/to/ipython/"}
#Python code to execute
```

The engine.path needs to lead to the folder containing the ipython executable (not the file itself). Currently the engine path must be specified, even if ipython is in your search path, I will try to fix this in the near future.

For details on how I figured out how knitr engines work or why it might be useful, check out my blog post about it.

ipythonKnitEngine <- function(options){
enginePath <- options$engine.path
if(grepl("/$", enginePath)) enginePath <- paste0(enginePath, "/")
engine <- paste0(enginePath, options$engine)
code <- paste("-c", shQuote(paste(options$code,
collapse = "\n")))
out <- system2(engine, code, stdout = TRUE, stderr = TRUE)
engine_output(options, options$code, out)
}
environment(ipythonKnitEngine) <- environment(knit_engines$set)
knit_engines$set(ipython = ipythonKnitEngine)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment