3 min read

Running Python in RStudio with reticulate

One of the main reasons I strongly prefer R to Python is that RStudio is far better than all Python IDEs I have used. I usually use Spyder for my Python IDE, but it has a lot of shortcomings compared to RStudio.

RStudio has added some Python support, for example in Rmarkdown files, in the past. Recently I discovered the R package reticulate which is closely integrated with RStudio and lets you run Python code more easily in RStudio. This blog post gives a great overview of how it works with examples. I’m going to go through some of the highlights here to give it a test run.

Enhanced RMarkdown with Python chunks

R Markdown files have allowed Python before, but now variables from these chunks can be accessed in following chunks using py$<variable name>. Similarly, Python code can access R variables using r.<variable name>. This is especially handy when you have certain tasks or functions that are already coded in one language but you want to use the results in the other.

Shared objects between Python and R

As mentioned above, you can access Python variables in R using py$<variable name> and R variables in python using r.<variable name>. Here’s an example, I’ve noted whether the code chunks are in R or Python.

(in R)

library(reticulate)
a <- 123

(in Python)

x = 456
print(x + r.a)
## 579.0

(in R)

py$x + a
## [1] 579

You can even pass data frames between them. The Python equivalent of a data frame is a Pandas data frame.

(in R)

df <- data.frame(a=c(1,2,3), b=c("a","b","c"))

(in Python)

print(r.df)
##      a  b
## 0  1.0  a
## 1  2.0  b
## 2  3.0  c

(in Python)

print(type(r.df))
## <class 'pandas.core.frame.DataFrame'>

Running a Python session in R

If you call reticulate::repl_python(), a Python session begins within the console. Typing exit will quit the session.

alt text

alt text

This doesn’t seem useful at first, but you can share variables between R and Python as shown above. Thus if you have code or libraries that you need in both R and Python, it should be easier to pass the data between them rather than writing the data to file and reading it back in.

Conclusion

Reticulate gives some cool capabilities for mixing R and Python. While this is useful when you have code in R and Python you want to mix, RStudio is not a replacement for a Python IDE, and likely won’t ever since it is focused on R. The lack of text highlighting or autosuggest for Python files in RStudio are two major deficiencies, both of which seem like easy problems to solve, though, so it isn’t too farfetched.