Python and R in the same notebook with %%R cell magic
I wanted to be able to execute python and R within the same jupyter notebook.
This time, I decided to do it the “quick and easy” (read: lazy) way and asked chatGPT.
It gave me a survey of several ways of accomplishing this, out of which I chose installing rpy2 package of python, then running a notebook with python kernel and using %%R cell magic at the beginning of each cell in which I want to execute code in R.
ChatGPT, again, offered several ways of installing rpy2, out of which the one that seemed best was: conda install -c conda-forge rpy2
This got stuck at some point, took several minutes and then timed out. What to do? I tried the other way chatGPT offered: pip install rpy2
And sure enough, this got rpy2 installed. The only problem was, the notebook was not working: it was giving me some unidentified identifier errors. Just paste me the full error traceback, chatGPT volunteered; so I did; and the verdict was, my rpy2 and R versions were not compatible.
Sure, I could see, how that could have happened: I had installed rpy2 with pip, whereas everything else had been installed with conda; it turns out that not everything that chatGPT might suggest will also be a good idea; who would have said that.
So it seems, I had better now uninstall rpy2 with pip and try to install it via conda, right?
Great idea, says chatGPT (but fortunately I realise that what really matters is that I think, too, that it is a great idea). So first I run: pip uninstall rpy2
And then, why was it that the conda installation of rpy2 was getting stuck? ChatGPT suggests it was due to resolving of the dependencies and that I might want to use an alternative resolver and/or create a new, separate environment in conda.
I thought I would like to avoid the former but the latter seemed like the way forward so I just executed the suggested command:
conda create -n pyr -c conda-forge
python=3.12
r-base
rpy2
jupyterlab
The environment got created without any errors.
Then (and at the beginning of each session) it is necessary to activate the environment with: conda activate pyr
Then the notebook server needs to be started with jupyter notebook --no-browser --port=8080 as described in my previous blog about anaconda installation (it seems that jupyter notebook is not present in this environment but jupyter lab can be used instead; it remains to be seen whether this is an adequate replacement).
In the notebook, the following needs to be executed in a notebook cell:
%load_ext rpy2.ipython
This time, the cell executes and the module loads with just a warning that it is missing numpty and pandas (this is something to be addressed and on the to-do list).
After that, code in R can be executed in cells starting with
%%R
If we need to import a variable called variablename from python into R, this can be done with
%%R -i variablename
(in subsequent R cells, variablename is known and it can be used)
Comments
No comments.