The reticulate package provides a comprehensive set of tools for interoperability between Python and R.
Reticulate embeds a Python session within your R session. It calls Python from R being able to translate objects within both packages. All the information can be found in the package documentation: https://rstudio.github.io/reticulate/.
> NOTE: This script was used as an Ice-Breaker of the R User Meeting held at BSC on 4/5/2023.
**How to use reticulate?**
There are a variety of ways to integrate Python code into R:
1. Importing Python modules
2. Sourcing Python scripts
3. Python REPL
4. Python in R Markdown (not shown in this file)
### 1. Importing Python modules
The import() function can import any Python module and call it’s functions directly from R.
The source_python() function can source a Python script the same way as source() an R script. Here, we first need to save a python script:
```py
import matplotlib.pyplot as plt
import numpy as np
# Data for plotting
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)
fig, ax = plt.subplots()
ax.plot(t, s)
ax.set(xlabel = 'time (s)', ylabel = 'x (m)',
title = 'Created with R')
ax.grid()
fig.savefig("plot2.png")
```
Then, we need to save the script. Let's call it ('test_reticulate_source.py').
Then, we source it from an R session:
```r
library(reticulate)
source_python("test_reticulate_source.py")
```
### 3. Python REPL
The repl_python() function creates an interactive Python console within R. Objects you create within Python are available to your R session (and vice-versa).