top of page
Writer's pictureDario Pittera

Using Python inside RStudio - reticulate package

At times, it might be helpful to use Python and R within the same environment. Indeed, we could make use of Python to wrangle the data in a more efficient way, and then us R packages to perform statistical analysis or to make use of R specific packages.


In my case, I prefer some packages for psychophysics written in R, but I am very used to Python to reshape and clean my data.


To start using Python in RStudio, we first need to install the "reticulate" library:



install.packages("reticulate")

# now use it in my code
library(reticulate)

Now we need to use an environment to run Python commands. In my case, I had an environment I created previously through "venv" containing all the libraries I needed, and called "psycho". At this point, we need a command to make R notebook to point to that environment:



# To enable Python in RStudio
use_virtualenv("address_to_env/psycho")

And that's it, really. Now we can just hit Ctrl+p to create a Python cell inside out RNotebook and run python commands as if we were inside, say, Jupyter Notebook.


At this point, we will have two separate environments: one with the variables created in Python, and one with the variables created in R.


To pass the variables from Python to R, I use:



my_R_var <- py$python_variable

Now I got my Python variable of interest into my R environment and I can continue the analysis with my R libraries!



Comments


bottom of page