Integrate Python in R

Statisticians Advancing in R
for Data Science

Mehdi Maadooliat, Jaihee Choi and Daniel Cirkovic

Marquette University
STAR-DS - SDSS 2026

Outline

  • Why integrate Python into R?
  • What is reticulate?
  • Installation & Setup
  • Importing Python Modules into R
  • Python Objects & Data Conversion
  • Sourcing Python Scripts in R
  • Accessing R Objects in Python
  • Working with Python Classes in R
  • reticulate in R Markdown & Quarto

Why integrate Python into R?

  • Access powerful Python libraries:
    • Deep Learning: PyTorch, TensorFlow, Keras
    • Machine Learning: scikit-learn, XGBoost, LightGBM
    • NLP: spaCy, HuggingFace transformers
    • Computer Vision: OpenCV
  • Combine the best of both worlds
    • R: data manipulation, statistics, visualization (ggplot2, dplyr)
    • Python: ML/AI, scripting, general programming
  • Avoid rewriting code or switching environments

What is 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

Installation & Setup

🧩 Install the reticulate package in R

install.packages("reticulate")

🐍 Ensure Python is installed
Use system Python, Anaconda, or a virtual environment. You can check the Python configuration in R:

library(reticulate)
py_available() # Check python availability
[1] FALSE

πŸ”— Bind to a specific Python version

# use_python("C://Users/your_username/AppData/Local/Programs/Python/Python313")
py_config() #Inspect current setup

Importing Python Modules into R

πŸ“¦ Use import() to bring Python modules into R

library(reticulate)
np <- import("numpy")
np$mean(c(1, 2, 3, 4))  
[1] 2.5

πŸ“¦ Use import_builtins() to import Python built-in functions

py_builtins <- import_builtins()
py_builtins$len(c(1, 2, 3))   
[1] 3

Sourcing Python Scripts in R

  • Use source_python() or py_run_file() to run .py scripts from R
  • Use py_run_string() to run inline Python code from R

πŸ“₯ Using source_python()

Variables become directly available in the R global environment

πŸ” Example:

Consider script.py file, includes following Python script:

y = 2
def square(x):
    return x **2

βœ… Works directly in R :

library(reticulate)
source_python("script.py")
print(y) 
[1] 2
square(4)
[1] 16

πŸ“₯ Using py_run_file()

Also runs the script, but…

  • ❌ Does not expose functions/variables directly in R
  • Variables and functions are stored in py$
py_run_file("script.py")
print(py$y)
[1] 2
py$square(4)
[1] 16

🧩 Using py_run_string()

  • Executes the string in the shared Python session
  • Variables created in Python are not added to R environment
  • Access Python variables in R using py$
py_run_string("
def square(x):
    return x ** 2
y = 5
")
py$y
[1] 5
py$square(4)
[1] 16

Data Conversion & Accessing R Objects in Python

πŸ” Automatic Data Conversion

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

Accessing R Objects from Python

πŸ” Example:
Let two following objects have been defined in R global environment:

library(reticulate)
x <- c(10, 20, 30)
f <- function(x) x^2

In Python we can access to these objects trough r object:

print(r.x)      
[10, 20, 30]
print(r.f(3))  
9

Exporting R Objects to Python

Use py$ assignment. In R:

library(reticulate)
x <- c(1, 2, 3)
py$x <- x        # Exports `x` to Python namespace
f <- function(n) n^2
py$f <- f        # Exports R function to Python

Now usable from Python:

print(x) 
[1.0, 2.0, 3.0]
print(f(5))
25.0

Exporting R Closure Functions to Python

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:

py$m <- mean
typeof(mean) 
[1] "closure"

In Python:

print(m([1, 2, 3, 4, 5]))     
3.0

Exporting R Builtin Functions to Python

Built-in functions in R are functions implemented in C (compiled) and embedded directly into the R interpreter.

⚠️ Builtin function needs wrapping. For example:

typeof(exp)
[1] "builtin"
py$e <- exp

In Python:

print(e(1))     
TypeError: 'PyCapsule' object is not callable

βœ… Solution: Wrap the builtin in a closure

e <- function(x) exp(x)
py$e <- e

In Python:

print(e(1))  
2.718281828459045

reticulate in R Markdown & Quarto

```{.python}
import numpy as np
x = np.arange(10)
```
  • Chunk engines: {python}, {python3}
  • Return to R:
r_vec <- py$x
  • Quarto YAML:
execute:
  echo: true

Shiny & Python Integration

🧬 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)

Resources & Further Reading

πŸ™ Thank you!

Questions & Discussion