R and Python in One Jupyter Notebook

R script on Jupyter notebook

Usually, Jupyter notebooks are using only one language at once: The one by the kernel (Python in your case).

You can use Script of Scripts (SoS) to make Jupyter polyglot to handle both python and R code in one Notebook. There is also reticulate and rpy2 to mix python and R code.

To show R results in Jupyter notebook, I recommend to export the R results in a language agnostic file format e.g. csv or json. These files can be easily imported in python afterwards.

Share variables between R and Python in jupyternotebook

The following Jupyter magic code demonstrates the use of R to compute 1+2+3 and save the result in variable rvar, then pass it to Python. The option -o rvar specifies that the variable rvar is required as output to Python environment.

%R -o rvar rvar=1+2+3

On another cell, you can use Python to manipulate that variable:

print(rvar)      # [1] 6
print(rvar[0]) # 6.0

For more complex example, with multiple output variables:

%%R -o X -o sdx -o xbar
X=c(1,4,5,7);
sdx=sd(X);
xbar=mean(X)

In (Python) Jupyter notebook, you get X, sdx, and xbar as the output. You can check them by running the code:

print('X:', X)
print('X[1]:', X[1])
print('sdx:', sdx)
print('xbar:', xbar)

More information about R magic can be found here.

Alternatively, you can use %Rpull and %Rget to get object from rpy2.

Edit

Updated reference link
as hinted by @lgautier in the comment.



Related Topics



Leave a reply



Submit