Search code examples
pythonrpycharm

How to pass an R variable to a Python variable in Pycharm?


I am new to Pycharm; however, I want to take advantage of my R and Python knowledge. I am a big fan of both languages, and I am constantly learning more about them. I am hoping to pass an R variable to a Python variable, similar to Jupyter Notebook. I could not find any example code anywhere of doing this.

R code

x <- 5

python code

# Some conversion method needs to be added
print(x)

Python Console

>>>5

Solution

  • This is possible because Jupyter provides its own Kernel that code runs in. This kernel is able to translate variables between languages.

    Pycharm does not provide a kernel, and instead executes Python code directly through an interpreter on your system. It's similar to doing python my_script.py. AFAIK vanilla Pycharm does not execute R at all.

    There are plugins for Pycharm that support R and Jupyter notebooks. You might be able to find one that does what you want.

    I usually solve this problem by simply adhering to the Unix philosophy:

    Rscript foo.R | python bar.py
    

    where foo.R prints the data to STDOUT and bar.py expects to read it from STDIN (you could also read/write from files). This approach of course requires you to define a clear interface of data between the scripts, rather than passing all the variables indiscriminately, which I don't personally mind because I do that anyway as a matter of design best practices.

    There are also packages like reticulate which will allow you to call one language from the other. This might be more useful if you like to switch languages a lot.