Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
RMarkdown Example using Python and R together
---
title: "Markdown Y'All"
author: "James Long"
date: "March 27, 2018"
output:
html_document: default
pdf_document: default
word_document: default
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## Run Some Python
We can use R Markdown to call Python code and return Python plots.
```{python, echo=FALSE}
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(12345)
df = pd.DataFrame(np.random.randn(100, 4), columns=list('ABCD'))
#pd.scatter_matrix(df, alpha=0.2, diagonal='kde')
df.A.plot.density(xlim=(-6,6))
plt.show()
print df.head()
```
## Grab Python Data Back Into R
Let's use the same data frame from Python and use it in R. To do this
we'll access the special `py` object created by the `reticulate` package.
```{r, echo=FALSE}
library(reticulate)
library(ggplot2)
ggplot(py$df, aes(A)) +
geom_density() +
xlim(-6, 6)
head(py$df)
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment