15.2 Run Python code and interact with Python

We know you love Python, so let’s make it super clear: R Markdown and knitr do support Python.

To add a Python code chunk to an R Markdown document, you can use the chunk header ```{python}, e.g.,

```{python}
print("Hello Python!")
```

You can add chunk options to the chunk header as usual, such as echo = FALSE or eval = FALSE. Plots drawn with the matplotlib package in Python are also supported.

The Python support in R Markdown and knitr is based on the reticulate package (Ushey, Allaire, and Tang 2024), and one important feature of this package is that it allows two-way communication between Python and R. For example, you may access or create Python variables from the R session via the object py in reticulate:

```{r, setup}
library(reticulate)
```

Create a variable `x` in the Python session:

```{python}
x = [1, 2, 3]
```

Access the Python variable `x` in an R code chunk:

```{r}
py$x
```

Create a new variable `y` in the Python session using R,
and pass a data frame to `y`:

```{r}
py$y <- head(cars)
```

Print the variable `y` in Python:

```{python}
print(y)
```

For more information about the reticulate package, you may see its documentation at https://rstudio.github.io/reticulate/.

References

Ushey, Kevin, JJ Allaire, and Yuan Tang. 2024. Reticulate: Interface to Python. https://rstudio.github.io/reticulate/.