Python in R Markdown?


R Markdown supports Python integration with the package reticulate.The nice thing about R Markdown is that it is the first scripting language I have ever learned. Therefore, I am almost too comfortable with it. It is my go to for most of my project because it’s so easy to get a proof of concept with new ideas. The downfall of it - until now - is that I was unaware that we could use PYTHON IN R MARKDOWN! Mind Blown! It sounds so easy too; duh, you could use Python in R Markdown this is 2018. But honestly, it has never crossed my mind to try… until now.

It is fairly easy to get started. Just install the package and run! Here is a list of all supported languages.

names(knitr::knit_engines$get())
install.packages("reticulate")
library(reticulate)

You will need to use "``` {python} CODE CHUNK HERE ```" to get started.

If you would like to use Python 3, simply use terminal and type which python and paste that directory in engine.path = '{PATH}'.

import matplotlib
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(19680801)
# example data
mu = 100  # mean of distribution
sigma = 15  # standard deviation of distribution
x = mu + sigma * np.random.randn(437)
num_bins = 50
fig, ax = plt.subplots()
# the histogram of the data
n, bins, patches = ax.hist(x, num_bins, density=1)
# add a 'best fit' line
y = ((1 / (np.sqrt(2 * np.pi) * sigma)) *
     np.exp(-0.5 * (1 / sigma * (bins - mu))**2))
ax.plot(bins, y, '--')
ax.set_xlabel('Smarts')
ax.set_ylabel('Probability density')
ax.set_title(r'Histogram of IQ: $\mu=100$, $\sigma=15$')
# Tweak spacing to prevent clipping of ylabel
fig.tight_layout()
plt.show()

This code is directly from matplotlib.org.

Back to blog

In God we trust. All others must bring data.

- W. Edwards Deming, Statistician