Search code examples
pythonrrpy2kaggle

How to use R and python in a Kaggle Notebook?


I would like to use both R and Python languages inside a Kaggle Kernel. Thus, when running

!pip install rpy2

inside a Kaggle Notebook I got the following error

Error: rpy2 in API mode cannot be built without R in the PATH or R_HOME defined. Correct this or force ABI mode-only by defining the environment variable RPY2_CFFI_MODE=ABI

I've found out a solution for users of Python within R, but a solution for calling R within Python in a Kaggle Kernel has not yet been provided.


Solution

  • One can notice that a Kaggle Kernel is using behind an anaconda environment. For example,

    /opt/conda/bin/python3.7
    

    Also, it is necessary to have R installed on this conda environment. Thus, we can use the subprocess library to run the following script for installing R

    import subprocess
    subprocess.run('conda install -c conda-forge r-base', shell=True)
    

    and the corresponding rpy2 package

    !pip install rpy2
    

    I have provided a notebook on Kaggle with a complete explanation. I'll appreciate your comments.