Skip to content

Instantly share code, notes, and snippets.

@thomasingalls
Last active October 6, 2017 03:54
Show Gist options
  • Save thomasingalls/24f75983b54b2c51fed3 to your computer and use it in GitHub Desktop.
Save thomasingalls/24f75983b54b2c51fed3 to your computer and use it in GitHub Desktop.
Use Rmarkdown with Python virtualenv

Motivation

Knitr beats the socks off of an iPython notebook. Both tools do the same job, but knitr doesn't require you to leave your established text editor workflow.

How to: Rmarkdown with Python virtualenv, for reproducibility.

Tested specifically on OS X 10.9, with R 3.1.2 and Anaconda python distribution.

  1. Calling an R script from the terminal will use the python version currently in the system PATH. If you need to specify a python 3.x or python 2.x environment, make your life easier and do it from the command line before you do anything else.
source activate py3k
  1. (optional sublimetext steps)
  • Open up sublime text via command line in the directory of interest. This loads sublimetext with the PATH variables you just set.
cd ~/git/directory
subl .
  • install Sublime Knitr (https://github.com/andrewheiss/SublimeKnitr) for convenience builds.
  • using template.Rmd in this gist, build your script. Save your file as fileName.Rmd.
  • cmd + B to build using sublimetext. Will output to fileName.md with an adjacent figure/ directory if you have images.
  1. Otherwise, if you're not in sublimetext, build your script from whatever, save as fileName.Rmd, and run the following command in your source activated terminal:
Rscript -e "library(knitr); knit('myfile.Rmd')"

h/t Maiasaura on stack overflow

```{r setup, include=FALSE}
# set global chunk options
library(knitr)
opts_chunk$set(cache=TRUE)
# if all chunks are python
#opts_chunk$set(engine = 'python')
# prefix all returned code with `Python >`
opts_chunk$set(comment='Python >')
```
<!--Start editing here-->
```{r chunk_label}
# runs R code
```
```{r python_chunk_label, engine='python'}
import platform
print(platform.python_version())
```
<!--End editing here-->
```{r python-session-info, engine='python'}
import sys
import IPython
modulenames = set(sys.modules)&set(globals())
allmodules = [sys.modules[name] for name in modulenames]
print(IPython.sys_info())
print(allmodules)
```
```{r r-session-info}
print(sessionInfo(), locale=FALSE)
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment