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.,

  1. ```{python}
  2. print("Hello Python!")
  3. ```

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 2020), 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:

  1. ```{r, setup}
  2. library(reticulate)
  3. ```
  4. Create a variable `x` in the Python session:
  5. ```{python}
  6. x = [1, 2, 3]
  7. ```
  8. Access the Python variable `x` in an R code chunk:
  9. ```{r}
  10. py$x
  11. ```
  12. Create a new variable `y` in the Python session using R,
  13. and pass a data frame to `y`:
  14. ```{r}
  15. py$y <- head(cars)
  16. ```
  17. Print the variable `y` in Python:
  18. ```{python}
  19. print(y)
  20. ```

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. 2020. Reticulate: Interface to Python. https://github.com/rstudio/reticulate.