Is it possible to run R and Python code in the same Jupyter notebook. What are all the alternatives available?
Which of above 3 options is reliable to run Python and R code snippets (sharing variables and visualizations) or is there a better option already?
Create a notebook file for use with R and Python Select the R instance where you want to install dependencies. Click Open JupyterLab. Select File > New > Notebook. Select the Python 3 kernel for your new notebook file.
Click the green play button on the r-tutorial environment and select the Open with Jupyter Notebook option. To create a new notebook for the R language, in the Jupyter Notebook menu, select New, then select R. To run the code, in the menu bar, click Cell then select Run Cells, or use the keyboard shortcut Ctrl-Enter.
Using R and Python together at the same time is incredibly easy if you already have your R scripts prepared. Calling them from Python boils down to a single line of code.
Using R in a Jupyter NotebookTo run a Jupyter Notebook with R, you need to create a conda environment and activate the kernel so Jupyter can recognize it. Then you can work with the R language in a notebook.
Yes, it is possible! Use rpy2.
You can install rpy2 with: pip install rpy2
Then run %load_ext rpy2.ipython
in one of your cells. (You only have to run this once.)
Now you can do the following:
Python cell:
# enables the %%R magic, not necessary if you've already done this %load_ext rpy2.ipython import pandas as pd df = pd.DataFrame({ 'cups_of_coffee': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 'productivity': [2, 5, 6, 8, 9, 8, 0, 1, 0, -1] })
R cell:
%%R -i df -w 5 -h 5 --units in -r 200 # import df from global environment # make default figure size 5 by 5 inches with 200 dpi resolution install.packages("ggplot2", repos='http://cran.us.r-project.org', quiet=TRUE) library(ggplot2) ggplot(df, aes(x=cups_of_coffee, y=productivity)) + geom_line()
And you'll get your pretty figure plotting data from a python Pandas DataFrame.
Using @uut's answer for running R in a jupyter notebook within python kernel (in MacOS), the following worked for me.
%%R
should always be at the start of the cell else you will get the error as shown in figure below
The following is the right way:
Also %load_ext rpy2.ipython
should come before %%R
hence put it in a different cell above it as shown in the figures.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With