Statisticians Advancing in R
for Data Science
Marquette University
STAR-DS - SDSS 2026
reticulate?PyTorch, TensorFlow, Kerasscikit-learn, XGBoost, LightGBMspaCy, HuggingFace transformersOpenCVggplot2, dplyr)reticulate?R package for interoperability with Python
Maintains a shared Python session accessible from R
Automatic conversion of many R types to Python and vice versa
Supports inline Python code in R Markdown and R scripts
π§© Install the reticulate package in R
π Ensure Python is installed
Use system Python, Anaconda, or a virtual environment. You can check the Python configuration in R:
π¦ Use import() to bring Python modules into R
source_python() or py_run_file() to run .py scripts from Rpy_run_string() to run inline Python code from Rsource_python()Variables become directly available in the R global environment
π Example:
Consider script.py file, includes following Python script:
py_run_file()Also runs the script, butβ¦
py$py_run_string()py$| R Object Type | Python Equivalent | Notes |
|---|---|---|
numeric, integer |
float, int |
Scalars or arrays |
logical |
bool |
TRUE β True |
character |
str or list[str] |
Vectorized strings β list |
vector, matrix |
numpy.ndarray |
Shape preserved |
data.frame |
pandas.DataFrame |
Column types preserved |
list (named) |
dict |
Keys from names |
list (unnamed) |
list |
Sequential list |
NULL |
None |
|
function (closure) |
Python callable | If inputs/outputs are convertible |
function (builtin) |
β PyCapsule | β οΈ not callable in Python |
S3/S4/R6 objects |
β PyCapsule | β οΈ Not convertible |
π Example:
Let two following objects have been defined in R global environment:
Use py$ assignment. In R:
A closure in R is simply a user-defined function created with the function() keyword. Itβs the most common type of function in R.
β A closure function Works directly. In R:
Builtin Functions to PythonBuilt-in functions in R are functions implemented in C (compiled) and embedded directly into the R interpreter.
β οΈ Builtin function needs wrapping. For example:
{python}, {python3}𧬠Run Python code dynamically inside a Shiny app using reticulate
library(shiny)
library(reticulate)
ui <- fluidPage(
actionButton("btn", "Compute in Python"),
verbatimTextOutput("out")
)
server <- function(input, output) {
observeEvent(input$btn, {
# Run Python code when button is clicked
py_run_string("import math; res = math.factorial(10)")
output$out <- renderText(py$res)
})
}
shinyApp(ui, server)Questions & Discussion