3. Why?
● Integration of Python into R workflow.
● Move between each package, using what’s best or
most familiar.
4. What you need to do first
● Install Reticulate package (which might be installed
already, depending on knitr version) .
● Reticulate uses the default Python; you can used the
function use_python("/usr/local/bin/python") to
choose alternates.
5. First Example: Run Python Command
library(reticulate)
os <- import("os")
os$listdir(".")
6. First Example: Results
[1] ".RData"
[2] ".Rhistory"
[3] ".Rproj.user"
[4] "Calling Python from R (AARUG Meeting, Oct 10,
2019).pptx"
[5] "Clustering File 1.Rmd"
[6] "Clustering-File-1.html"
And so on
7. Second Example: Import and
Wrangle Data
py_run_string("import pandas as pd")
py_run_string("flights_python = pd.read_csv('Data/flights.csv')")
py_run_string("flights_python_dest_ORD =
flights_python[flights_python['dest']=='ORD']")
py_run_string("flights_python_dest_ORD=flights_python_dest_ORD.dropna
()")
py_run_string("flights_python_dest_ORD_shape
=flights_python_dest_ORD.shape")
10. In Rmarkdown/knitr
Use code chunks
```{python trial_run}
import pandas as pd
flights_python = pd.read_csv("Data/flights.csv")
flights_python_dest_ORD = flights_python[flights_python['dest']=='ORD']
flights_python_dest_ORD=flights_python_dest_ORD.dropna()
flights_python_dest_ORD_shape =flights_python_dest_ORD.shape
print(flights_python_dest_ORD_shape)
```
11. Interactive Python in R
The command repl_python() will open an interactive
python session.
The cursor will change to ‘>>>’.
12.
13. References
● ‘R Interface to Python’ https://rstudio.github.io/reticulate/
● ‘R Markdown Python Engine’
https://rstudio.github.io/reticulate/articles/r_markdown.html#engine-
setup
● Vignette on GitHub:
https://github.com/rstudio/reticulate/blob/master/vignettes/calling_pytho
n.Rmd
● ‘R and Python: Using reticulate to get the best of both worlds’
(https://www.r-bloggers.com/r-and-python-using-reticulate-to-get-the-
best-of-both-worlds/)
● Nabih Ibrahim Bawazir (LinkedIn)
https://www.linkedin.com/in/nabihbawazir/