%%{init: {'theme': 'base', 'look': 'classic', 'themeVariables': {'fontFamily': 'monospace'}}}%%
flowchart TD
subgraph PkgLayer ["<strong>Packages</strong>"]
Pkgs("R + Python<br>packages")
end
subgraph SysLayer ["<strong>System</strong>"]
Lang("R + Python<br>versions")
Libs("system<br>libraries")
OS("operating<br>system")
end
subgraph HwLayer ["<strong>Hardware</strong>"]
VHw("virtual<br>hardware")
PHw("physical<br>hardware")
end
Pkgs -->|"built for"| Lang
Pkgs -->|"link to"| Libs
Lang -->|"compiled for"| OS
Libs -->|"compiled for"| OS
OS -->|"runs on"| HwLayer
VHw -->|"runs on"| PHw
style Pkgs fill:#D2562B,stroke:#000000,stroke-width:1px,color:#ffffff
style Lang fill:#2A6F77,stroke:#000000,stroke-width:1px,color:#ffffff
style Libs fill:#2A6F77,stroke:#000000,stroke-width:1px,color:#ffffff
style OS fill:#2A6F77,stroke:#000000,stroke-width:1px,color:#ffffff
style VHw fill:#485466,stroke:#000000,stroke-width:1px,color:#ffffff
style PHw fill:#485466,stroke:#000000,stroke-width:1px,color:#ffffff
style PkgLayer fill:#fbf7ec,stroke:#D2562B,color:#1B2A41
style SysLayer fill:#fbf7ec,stroke:#2A6F77,color:#1B2A41
style HwLayer fill:#fbf7ec,stroke:#485466,color:#1B2A41
Lab 1: Environments as Code
This lab shows how to create isolated, reproducible package environments with renv (R) and venv (Python), which every lab that follows depends on. The first lab includes two Quarto documents:
_labs/lab01/
├── eda-basic.qmd
└── model-basic-py.qmdComprehension questions
“Why does difficulty increase as the level of required reproducibility increase for a data science project. In your day-to-day work, what’s the hardest reproducibility challenge?”
Each layer of the environment we need to reproduce adds work, and the work grows faster than the payoff. Packages are cheap to capture: renv.lock or requirements.txt records them, and one command restores them. The system layer is harder, because a lockfile can record the R version but can’t install it or the operating system underneath it. At the far end, some regulated industries have to rerun an analysis exactly a decade later, which means keeping the physical hardware running. That’s why the chapter calls a completely reproducible environment “a fool’s errand.”
The hardest challenge I’ve run into is in the system layer. It’s impossible to know what system requirements developers might need (for both Python and R), and you might not have the level of control you want on the server.
“There’s a table of the layers of the data science environment above. It names six items across three layers. Draw a mental map of the relationships between these six items. Pay particular attention to why the higher layers depend on the lower ones.”
Each item is built for, or runs on, the item below it, so a change at the bottom reaches everything above it:
Packages are built for a specific language version and operating system, and many of them link to system libraries ({sf} needs GDAL, for example). The R and Python interpreters and the system libraries are compiled for the operating system. The operating system runs on virtual hardware (an EC2 instance), and the virtual hardware runs on physical servers in a data center. Also, having old system libraries on the operating system can be enough to block R installations.
“What are the two key attributes of environments as code? Why do you need both of them? Are there cases where you might only care about one?”
Isolation and portability. The package environment is isolated, so other work on the same machine can’t disrupt it, and it can be captured and moved to another machine. These are the first two takeaways in Project-oriented workflows below.
Each one protects something different. Isolation keeps the project working when I update a package for another project. Capturing the environment lets a colleague, a server, or me in six months rebuild it.
Sometimes one is enough. A throwaway analysis I’ll delete next week needs isolation but not a lockfile. Inside a container, the container already provides the isolation, so the lockfile is the part I still need.
“Draw a mental map of the relationships between the following: package repository, package library, package, project-level-library, .libPaths() (R) or sys.path (Python), lockfile.”
The renv and venv diagrams below map these items. A package repository (CRAN or PyPI) holds the current and archived versions of each package. Installing a package puts one version in a package library, which holds at most one version of each package. Libraries can be system, user, or project level, and a project-level library holds one project’s packages.
.libPaths() (R) and sys.path (Python) list the libraries in search order. Activating renv or venv puts the project-level library first. The lockfile (renv.lock or requirements.txt) records each package and its version, so we can rebuild the library from the repository.
“Why is it a bad idea to share package libraries? What’s the best way to collaborate with a colleague using an environment as code? What commands will you run in R or Python to save a package environment and restore it later?”
Package installs are specific to the operating system and language version, so a library built on my laptop might not work on a colleague’s machine. Package files are also large. It’s much easier to share a lockfile instead: keep renv.lock or requirements.txt in Git, and each machine installs its own packages from it.
In R, renv::snapshot() saves the environment and renv::restore() restores it. In Python, python3 -m pip freeze > requirements.txt saves it and python3 -m pip install -r requirements.txt restores it.
Project-oriented workflows
Key takeaways:
Each project should have an isolated package environment that preserves the names and versions.
The project’s dependencies/requirements should be captured in a way that makes it exportable/transferable to another machine.1
Each project should have a virtual environment in a standalone directory that documents everything the project needs (usually in a GitHub or GitLab repo).2
Virtual environments
As do4ds notes, venv and renv “keep user-level package caches of the actual packages and use symlinks, so only one copy of the package is installed.”
renv
First, read the documentation on project level management with renv and using renv with Quarto.
I’ve summarized the steps below:
Create a new R project-local environment
install.packages("renv") renv::init()Install packages into the renv-managed environment
install.packages(c("tidyverse", "shiny", "ggplot2"))Snapshot the state of the environment and package versions in the lock file (
renv.lock)renv::snapshot()To deactivate the environment, close the R session.
renvprojects are automatically reactivated the next time the project is opened. Restore the environment on a new system with:renv::restore()
The renv-eda-basic project
To demonstrate how to use renv, I’ve copied the eda-basic.qmd file into its own project folder (renv-eda-basic):
_labs/lab01/renv-eda-basic/
└── eda-basic.qmdThen I ran renv::init():
renv::init()Initiating renv in a project root directory will create the .Rprofile and renv.lock files and a renv/ folder:
_labs/lab01/renv-eda-basic/
├── .Rprofile
├── .gitignore
├── eda-basic.qmd
├── renv
│ ├── .gitignore
│ ├── activate.R
│ └── settings.json
├── renv-eda-basic.Rproj
└── renv.lockThe renv-eda-basic.Rproj file comes from RStudio, not renv::init(). It helps enforce project-oriented workflows (but .Rproj files are specific to RStudio).
To install the packages, we can use install.packages() or pak::pak() for more flexible installations:
install.packages("pak")
pak::pak(c("tidyverse", "shiny", "ggplot2"))Create a snapshot (i.e., the current versions of R and any installed packages, along with the R repositories) with renv::snapshot():
renv::snapshot()The dependencies are saved in the renv.lock file, which should be committed to version control.
To make sure the dependencies in the renv.lock file have been installed (i.e., after cloning), run:
renv::restore()The diagram below maps how packages flow between CRAN, the renv cache, the project library, and the lockfile:
%%{init: {'theme': 'base', 'look': 'classic', 'themeVariables': {'fontFamily': 'monospace'}}}%%
flowchart TD
%% External sources
CRAN("CRAN/<br>GitHub/...")
%% Local components
SysLib("system<br>library")
ProjLib("project<br>library")
RenvCache[("renv<br>cache")]
Lockfile[("lockfile")]
%% Subgraph for "your computer" vs "the internet"
subgraph Internet ["<strong>Internet</strong>"]
CRAN
end
subgraph Computer ["<strong>Computer</strong>"]
SysLib
ProjLib
RenvCache
Lockfile
end
%% Connections with function labels
SysLib -->|"<strong>init()</strong>"| ProjLib
CRAN -->|"<strong>install()</strong><br><strong>update()</strong>"| RenvCache
RenvCache -->|"renv"| ProjLib
ProjLib <-->|"<strong>status()</strong>"| Lockfile
ProjLib -->|"<strong>snapshot()</strong>"| Lockfile
Lockfile -->|"<strong>restore()</strong>"| ProjLib
%% styling
%% classDef default fill:#F2E6C2,stroke:#2A6F77,color:#1B2A41
style CRAN fill:#5B8C5A,stroke:#000000,stroke-width:1px,color:#ffffff
style SysLib fill:#2A6F77,stroke:#000000,stroke-width:1px,color:#ffffff
style RenvCache fill:#D2562B,stroke:#000000,stroke-width:1px,color:#ffffff
style ProjLib fill:#2A6F77,stroke:#000000,stroke-width:1px,color:#ffffff
style Lockfile fill:#485466,stroke:#000000,stroke-width:1px,color:#ffffff
style Internet fill:#fbf7ec,stroke:#5B8C5A,color:#1B2A41
style Computer fill:#fbf7ec,stroke:#2A6F77,color:#1B2A41
venv
Read the documentation on Python virtual environments and using venv with Quarto.
I’ve summarized the steps below:
Create new Python 3 virtual environment in the
.venvdirectorypython3 -m venv .venvActivate the environment
source .venv/bin/activateUse
pipto install packages into your environmentpython3 -m pip install jupyter matplotlib pandasDeactivate an environment
deactivateSave environment
python3 -m pip freeze > requirements.txtRestoring environment
python3 -m pip install -r requirements.txt
The venv-model-basic-py project
Use the Terminal to navigate to the venv-model-basic-py folder and create the Python virtual environment:
python3 -m venv .venvThis will create a .venv/ folder inside venv-model-basic-py.
_labs/lab01/venv-model-basic-py/
├── .venv
│ ├── bin
│ ├── include
│ ├── lib
│ └── pyvenv.cfg
└── model-basic-py.qmdTo activate the virtual environment, run the following in the Terminal:
source .venv/bin/activateThis should change the Terminal prompt from:
Bash@MacBook venv-model-basic-py$ to:
(.venv) Bash@MacBook venv-model-basic-py$Now we can install the required Python packages (we include jupyter for interactive outputs):
pip install palmerpenguins pandas numpy scikit-learn jupyterTo store the installed packages, save them to a requirements.txt file with pip freeze:
python3 -m pip freeze > requirements.txtThe diagram below maps how packages flow between PyPI, the pip cache, the virtual environment, and requirements.txt:
%%{init: {'theme': 'base', 'look': 'classic', 'themeVariables': {'fontFamily': 'monospace'}}}%%
flowchart TD
%% External sources
PyPI("PyPI/<br>GitHub/...")
%% Local components
SysPython("system<br>Python")
VirtEnv("virtual<br>environment")
PipCache[("pip<br>cache")]
Requirements[("requirements.txt")]
%% Subgraph for "your computer" vs "the internet"
subgraph Internet ["<strong>Internet</strong>"]
PyPI
end
subgraph Computer ["<strong>Computer</strong>"]
SysPython
VirtEnv
PipCache
Requirements
end
%% Connections with function labels
SysPython -->|"<strong>python -m venv</strong>"| VirtEnv
PyPI -->|"<strong>pip install</strong><br><strong>pip install -U</strong>"| PipCache
PipCache -->|"pip"| VirtEnv
VirtEnv <--->|"<strong>pip list</strong><br><strong>pip show</strong>"| Requirements
VirtEnv -->|"<strong>pip freeze</strong>"| Requirements
Requirements -->|"<strong>pip install -r</strong>"| VirtEnv
%% Additional workflow arrows
VirtEnv -.->|"<strong>source activate</strong><br><strong>deactivate</strong>"| VirtEnv
%% Styling
style PyPI fill:#5B8C5A,stroke:#000000,stroke-width:1px,color:#ffffff
style SysPython fill:#5B8C5A,stroke:#000000,stroke-width:1px,color:#ffffff
style VirtEnv fill:#2A6F77,stroke:#000000,stroke-width:1px,color:#ffffff
style PipCache fill:#D2562B,stroke:#000000,stroke-width:1px,color:#ffffff
style Requirements fill:#485466,stroke:#000000,stroke-width:1px,color:#ffffff
style Internet fill:#fbf7ec,stroke:#5B8C5A,color:#1B2A41
style Computer fill:#fbf7ec,stroke:#2A6F77,color:#1B2A41
Rendering with Python
To render, use the following in the Terminal:
quarto preview model-basic-py.qmd --no-browser --no-watch-inputsQuarto uses the first Python on the PATH, so rendering with the virtual environment active uses .venv. Or we can set the Python interpreter with the QUARTO_PYTHON environment variable in the Terminal:3
export QUARTO_PYTHON="${PWD}/.venv/bin/python3"If you’re working inside RStudio or Posit Workbench, consider letting reticulate manage the Python environment:
library(reticulate)
use_virtualenv("myenv", required = TRUE)
virtualenv_install(
envname = "myenv",
packages = c("palmerpenguins", "pandas", "numpy",
"scikit-learn", "jupyter"))This ensures RStudio uses a known-good Python environment.
Now, if we open the model-basic-py.qmd file in RStudio and click the Render button in the toolbar we should see the rendered output.
Recap
Each project gets its own isolated, transferable package environment. In R,
renv::init()creates the project library andrenv.lock,renv::snapshot()records the package versions, andrenv::restore()reinstalls them on another machine.In Python,
python3 -m venv .venvcreates the environment andsource .venv/bin/activateturns it on.pip freeze > requirements.txtcaptures the installed packages, andpip install -r requirements.txtrestores them.Quarto has to be told which Python interpreter to use. We can render with the virtual environment active, set
QUARTO_PYTHONto.venv/bin/python3in the Terminal, or letreticulatemanage the environment inside RStudio.
Next, Modeling in Python walks through the code in model-basic-py.qmd.