{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## Using R in a Python notebook With rpy2\n", "The rpy2 package provides a way of using R components as python objects." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from rpy2.robjects import r, pandas2ri\n", "pandas2ri.activate()\n", "r.data('iris')\n", "r['iris'].head(2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Using Native R Code Cells in a Python Notebook\n", "\n", "We can also use cell magic to allow us to cross back and forth between `python` and `R` code cells." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%load_ext rpy2.ipython\n", "import pandas as pd\n", "df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C':[7,8,9]})\n", "df" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%%R -i df -o rdf\n", "library(ggplot2)\n", "\n", "rdf='My R created variable'\n", "ggplot(df) + geom_point(aes(x=A,y=B,size=C)) + ggtitle(rdf)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.1" } }, "nbformat": 4, "nbformat_minor": 2 }