To add a Python code chunk to an R Markdown document, you can use the chunk header , e.g.,
The Python support in R Markdown and knitr is based on the reticulate package (), 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:
x = [1, 2, 3]
Access the Python variable `x` in an R code chunk:
```{r}
py$x
```
and pass a data frame to `y`:
```{r}
py$y <- head(cars)
```
Print the variable `y` in Python:
```{python}
```
Ushey, Kevin, JJ Allaire, and Yuan Tang. 2020. Reticulate: Interface to Python. https://github.com/rstudio/reticulate.