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)
```
`x` in the Python session:
Create a variable
```{python}
x = [1, 2, 3]
```
`x` in an R code chunk:
Access the Python variable
```{r}
py$x
```
`y` in the Python session using R,
Create a new variable `y`:
and pass a data frame to
```{r}
py$y <- head(cars)
```
`y` in Python:
Print the variable
```{python}
print(y)
```
For more information about the reticulate package, you may see its documentation at https://rstudio.github.io/reticulate/.