Using R in Jupyter Notebook

R has started to gain momentum in data science due to its easy-to-use and full of statistic packages. For longtime Python user, I want to run some R commands within Jupyter for pratical reasons, like some collaborators are using R for some tasks or just convenience. This article will show you how to do it.

  • Setup environment

Install R essentials in your current environment:

conda install -c r r-essentials

These ‘essentials’ include the packages dplyr, shiny, ggplot2, tidyr, caret and nnet. 

You can also create a new environment just for the R essentials:

conda create -n my-r-env -c r r-essentials

Now you’re all set to work with R in Jupyter.

How about install new packages in R for my usage in Jupyter?

There are two ways of doing it: 1. build a Conda R package by running:

conda skeleton cran xxx conda build r-xxx/

Or you can install the package from inside of R via install.packages() or devtools::install_github. But with one change: change the destination to conda R library.

install.packages(“xxx”,”home/user/anaconda3/lib/R/library)

  • Into good hands

THe interactivity comes mainly from the so-called “magic commands” which allows you to switch from Python to command line instructions (like ls, cat etc) or to write code in other languages such as R, Scala, Julia, …

After open Jupiter notebook, you should be able to see R in the console:

1

To switch from Python to R, first download the following pacakge:

%load_ext rpy2.ipython

After that, start to use R with the %R magic command.

# Hide warnings if there are any
import warnings
warnings.filterwarnings(‘ignore’)
# Load in the r magic
%load_ext rpy2.ipython
# We need ggplot2
%R require(ggplot2)
# Load in the pandas library
import pandas as pd
# Make a pandas DataFrame
df = pd.DataFrame({‘Alphabet’: [‘a’, ‘b’, ‘c’, ‘d’,’e’, ‘f’, ‘g’, ‘h’,’i’],
‘A’: [4, 3, 5, 2, 1, 7, 7, 5, 9],
‘B’: [0, 4, 3, 6, 7, 10,11, 9, 13],
‘C’: [1, 2, 3, 1, 2, 3, 1, 2, 3]})
# Take the name of input variable df and assign it to an R variable of the same name
%%R -i df
# Plot the DataFrame df
ggplot(data=df) + geom_point(aes(x=A, y=B, color=C))