'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 1:[1]

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.

Solution 2:[2]

Thanks for the above answer! That is great. I did find solution that could help other people that use pycharm. If you have installed the R plug in option, you can use the following code.

Python code to save to feather file:

```
import pyarrow.feather as feather

data = pd.read_csv('C:/Users/data.csv')
feather.write_feather(data, 'C:/Users/data.feather')
```

R code to retrieve feather file

```
library(tidyverse)
library(feather)
library(arrow)

data <- arrow::read_arrow('C:/Users/data.feather')
print(data)
```

However, this process seems very similar to writing a file to csv in Python, then uploading the csv into R. There could be some type of lightweight storage difference, speed processing, and language variable agnostic/class translation. Below is the official documentation: Git: https://github.com/wesm/feather Apache Arrow: https://arrow.apache.org/docs/python/install.html RStudio: https://www.rstudio.com/blog/feather/

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jessica
Solution 2 Zane Cantrell