R and Python in One Document · Your Own Runbook

Week 8 · Tuesday, Nov 17 · Lecture

Dr. Marcela Alfaro Córdoba

Today’s plan

Time What
1:30 Runbook render: your questions from Thursday
1:40 Why put two languages in one document
1:45 How it works: knitr + reticulate
2:00 Passing data between R and Python
2:20 renv: the packages are part of the project
2:30 Workshop: your own runbook
3:00 Before Thursday

Learning goals: run Python chunks inside a Quarto document next to R; move a data frame from R to Python and back, checking what changed on the way; restore and update a project’s package versions with renv; get your own project to render from a runbook.

No AI in today’s exercises. In the workshop you’re working on your project, where AI is allowed with disclosure.

Runbook render: your questions

⏱ 10 min

Open time, not graded. Bring the problems from the “Runbook render” and “Break it” Ed threads.

If nobody starts: why does renv::restore() install packages you already have? Why did the first render take longer than the second? What is execute-dir: project for? Why are data/processed/ and output/ empty after a fresh clone?

Two languages, one document

Why?

  • Your team has a collaborator who works in Python, or a method only exists in a Python library
  • Part of the pipeline already exists as a Python script, and rewriting it is a risk
  • You’ll meet both in almost any data job. Reading the other language is a skill

One document, one session, one render: the Python step is reproducible too.

The alternative, “run this Python script first, then render”, is a step a reader will forget.

How it works

```{r}
#| label: python-setup
library(reticulate)
py_require("pandas>=2.2")
```

```{python}
#| label: py-correlations
import sys
sys.path.insert(0, "python")
from summarize import regionCorrelations

correlations = regionCorrelations(r.analysis, 2007)
correlations
```
  • A chunk that starts with ```{python} runs Python
  • The document has R chunks, so Quarto uses the knitr engine, and knitr runs Python through the R package reticulate. Both live in one session
  • py_require() declares the Python packages. The first render downloads Python + pandas into a cache; nobody installs Python by hand

A .qmd with only Python chunks uses the jupyter engine instead. Same chunks, different engine.

Passing objects

From To Write Example
R Python r. r.analysis in a {python} chunk
Python R py$ py$correlations in an {r} chunk
knitr::kable(py$correlations, digits = 2)
#> |region                     | n_countries| correlation|
#> |:--------------------------|-----------:|-----------:|
#> |North America              |           2|       -1.00|
#> |South Asia                 |           4|       -0.95|
#> |Middle East & North Africa |          20|       -0.75|
#> |...                        |            |            |
#> |Europe & Central Asia      |          30|        0.26|

Read n_countries before the correlation. A correlation of −1 from two countries tells you nothing.

What changes on the way

reticulate converts types for you. Usually:

R Python
data.frame / tibble pandas DataFrame
numeric vector, length > 1 NumPy array (in a data frame: a column)
length-1 vector a single number or string
named list dict
NA in a numeric column NaN
factor pandas Categorical

Check row counts and missing values on both sides.

Same habit as after a join: nrow(analysis) in R, len(r.analysis) and r.analysis.isna().sum() in Python. Also: Python counts from 0. The first row is df.iloc[0].

Your turn: a Python chunk of your own

⏱ 15 min

In the example runbook, after the py-correlations chunk:

  1. Add a {python} chunk that counts countries per income group in 2007, from r.analysis.
    Hint: df[df["year"] == 2007].groupby("income_group").size()
  2. Check: how many rows does r.analysis have in Python? Is it the same as nrow(analysis) in R?
  3. Bring the result back: in an {r} chunk, look at py$.... What type did it become? (class())
  4. Render. Then add a sentence with inline code that reports the largest income group

What we found

import pandas as pd
by_income = (
    r.analysis[r.analysis["year"] == 2007]
    .groupby("income_group")
    .size()
    .reset_index(name="n_countries")
)
len(r.analysis)       # 1361, same as nrow(analysis)
class(py$by_income)    #> [1] "data.frame"
  • Without reset_index(), .size() returns a pandas Series, which comes back to R as a named array (class() says "array"), not a data frame
  • reset_index(name = ...) gives a DataFrame, which comes back as a data frame
  • Inline: `r py$by_income$income_group[which.max(py$by_income$n_countries)]`

renv

The packages are part of the project

Your analysis depends on versions. A dplyr update can change a default; a render that worked in November can fail in March.

You want to… Run What it does
start using renv in your project renv::init() Project library + renv.lock + .Rprofile
get the versions in renv.lock (after cloning) renv::restore() Installs exactly those versions
record a package you just added renv::snapshot() Updates renv.lock. Commit it
see what’s out of sync renv::status() Lists used-but-not-recorded packages

Commit renv.lock, .Rprofile, renv/activate.R and renv/settings.json. Don’t commit renv/library/ (renv’s own .gitignore handles it). Python packages are recorded by py_require(), in the runbook itself.

Your runbook

Workshop: start your own run-analysis.qmd

⏱ 30 min

  1. Copy template/run-analysis-template.qmd from the example repo into your project’s top folder, as run-analysis.qmd
  2. Fill in “The project at a glance”: question, data table with sources and licenses, folder tree
  3. One step at a time: move code from your mid-quarter report into R/01-...R, R/02-...R, and source() it from a chunk. Render after each step
  4. renv::init(), render, commit
  5. Pairs: both partners render it on their own laptops

Your mid-quarter .qmd is not wasted: its code goes into the scripts, its text goes into the runbook. AI is allowed here with disclosure; note it in your “AI use” section as you go. I’ll come around.

Key points

  • {python} chunks run next to {r} chunks; with any R chunk, Quarto uses knitr + reticulate, and both share one session
  • r.x reads R objects in Python; py$x reads Python objects in R
  • Conversions are automatic but not invisible: check rows and NA/NaN on both sides; a pandas Series comes back as a named array, not a data frame
  • py_require() puts the Python dependencies in the document
  • renv: init() once, restore() after cloning, snapshot() after adding a package, and commit renv.lock
  • Your runbook: one chunk per step, source() the scripts, render after each change

Before Thursday

Thursday, Nov 19: writing good software, using AI with rules, and AI ethics. Tuesday, Nov 24: peer code review, in class, on your repository. It must render from a fresh clone by then.