R Markdown

Reticulate is an R library that allows users to embed Python in R. It is very powerful - for example allowing users to include chunks of Python in RMarkdown documents. First off, load the package:

library(reticulate)

Then we can start working with Python - (providing it is already there on your system). Here is some Python embedded in the Rmarkdown.

import pandas as pd
import numpy as np
import seaborn as sb
meow = np.array([[-1,1,1],[1,1,-1],[1,1,1]])
print(meow)
## [[-1  1  1]
##  [ 1  1 -1]
##  [ 1  1  1]]
print(meow.shape)
## (3, 3)

You can refrence the python objects you have created using R:

library(reticulate)
py$meow
##      [,1] [,2] [,3]
## [1,]   -1    1    1
## [2,]    1    1   -1
## [3,]    1    1    1
woof <- solve(py$meow)
woof
##      [,1] [,2] [,3]
## [1,] -0.5  0.0  0.5
## [2,]  0.5  0.5  0.0
## [3,]  0.0 -0.5  0.5

The same trick works in the other direction - woof is an R object created above…

…. and here it is inside Python:

print(r.woof)
## [[-0.5  0.   0.5]
##  [ 0.5  0.5  0. ]
##  [ 0.  -0.5  0.5]]
from numpy.linalg import inv
print(inv(r.woof))
## [[-1.  1.  1.]
##  [ 1.  1. -1.]
##  [ 1.  1.  1.]]
print(meow - inv(r.woof))
## [[ 0.  0.  0.]
##  [ 0.  0.  0.]
##  [ 0.  0.  0.]]

Graphics also works!

import matplotlib.pyplot as plt
phi = np.arange(0,3*np.pi,0.0025)
x = np.cos(5*phi)
y = np.sin(3*phi)
plt.plot(x,y)
plt.show()

Quite fancy stuff…

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
fig = plt.figure()
ax = Axes3D(fig)
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.viridis)
plt.show()

import matplotlib.tri as mtri
n_radii = 8
n_angles = 36
# Make radii and angles spaces (radius r=0 omitted to eliminate duplication).
radii = np.linspace(0.125, 1.0, n_radii)
angles = np.linspace(0, 2*np.pi, n_angles, endpoint=False)
# Repeat all angles for each radius.
angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
# Convert polar (radii, angles) coords to cartesian (x, y) coords.
# (0, 0) is manually added at this stage,  so there will be no duplicate
# points in the (x, y) plane.
x = np.append(0, (radii*np.cos(angles)).flatten())
y = np.append(0, (radii*np.sin(angles)).flatten())
# Compute z to make the pringle surface.
np.random.seed(6677)
z = np.sin(x*y) + 1.5/(1+x*x + y*y) +  np.random.normal(0.0, 0.05, x.size)
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_trisurf(x, y, z, linewidth=0.2, antialiased=True,cmap=cm.copper)
plt.show()