4  Python and R

4.1 Setting Up Python

Python is the language most of the infrastructure in this book is written in and expects. NumPy, pandas and scikit-learn cover the numerical and modelling work; almost everything else — web frameworks, cloud SDKs, orchestration tools — has a Python client whether or not it has an R one. That reach is the practical argument for it, more than anything about the language itself.

4.1.1 Installing Python

There are two routes worth taking, and the book gives instructions for both throughout. Pick one now; you can add the other later without undoing anything.

Route Take it when
uv Default for new work. A single binary that installs Python versions, creates environments, and installs packages, quickly
Miniforge (conda) You need packages that aren’t pure Python — GDAL and the geospatial stack, CUDA-enabled PyTorch, much of bioinformatics — or your team already standardises on conda

The numerical stack itself works fine either way. NumPy, pandas, scikit-learn and matplotlib all publish prebuilt wheels for Windows, macOS and Linux, so uv installs them without needing a compiler on your machine. Conda’s advantage shows up further out, where a package depends on system libraries that aren’t Python at all and someone has to resolve those too.

Two other options you’ll see mentioned, for completeness. Anaconda is the batteries-included conda distribution; it works, but its Terms of Service have restricted free commercial use above a size threshold since 2020 — 200 employees as of writing, extended by a 2024 update to government bodies and non-profits of the same size. As with any licence term, check Anaconda’s current terms rather than this paragraph. Miniforge is the community-maintained equivalent with no such restriction, which is why this book points at it. System Python from python.org, Homebrew or apt is fine as a base, but you’ll still want per-project environments on top of it.

4.1.1.1 Route 1: uv

Install it once, from your terminal:

# macOS / Linux
curl -LsSf https://astral.sh/uv/install.sh | sh
# Windows PowerShell
powershell -c "irm https://astral.sh/uv/install.ps1 | iex"

Both download a script and run it in one step, which is the method Astral documents. The Command Line explains what you’re agreeing to when you do that, and when to download and read the script first instead.

Close and reopen your terminal so the new command is on your PATH, then check it:

uv --version

uv doesn’t need a system Python. uv venv --python 3.13 downloads that version if you don’t have it, which means the Python your project runs on is something you choose per project rather than something your operating system decided for you.

4.1.1.2 Route 2: Miniforge (or Anaconda)

  1. Visit the Miniforge releases page (or the Anaconda download page if you prefer)
  2. Download the appropriate installer for your operating system
  3. Run the installer and follow the prompts

During installation on Windows, you may be asked whether to add the installation to your PATH environment variable. Leave this unchecked and use the Miniforge Prompt (or Anaconda Prompt) from the Start menu, which avoids conflicts with other Python installations on your system.

The “PATH” is like an address book that tells your computer where to find programs when you type their names. Adding your conda install to PATH means you can use Python from any command prompt, but it could cause conflicts with other versions of Python on your system.

Miniforge defaults to conda-forge — conda calls package repositories “channels” — which is maintained by the community rather than by a company, and is the reason Miniforge carries none of Anaconda’s licensing conditions.

Open a new terminal (or the Miniforge Prompt on Windows) and check both commands:

python --version
conda --version
ImportantDon’t install packages into the base installation

The next thing most people do is pip install pandas and carry on. Resist it. Packages installed globally accumulate, conflict, and eventually break each other in ways that are genuinely painful to unpick — and nothing records what you installed, so the analysis you write today may not run tomorrow.

Create a per-project environment first. That is the whole subject of the Reproducible Environments chapter, and it’s worth reading before you install your second package. The short version:

# uv - the environment lives in the project directory
uv venv --python 3.13

# conda - the environment lives in a central location, under a name
conda create -n myproject python=3.13
conda activate myproject

Install into that, not into the base installation or your system Python.

4.1.2 Using Jupyter Notebooks

A Jupyter notebook interleaves code, its output, and your prose in one document — a lab notebook you can re-run. It’s where most exploratory Python work happens.

Neither uv nor Miniforge installs Jupyter for you. Make a directory to work through this book in, then create an environment there with what the next few chapters need.

With uv, the environment is a .venv directory inside the project:

mkdir rbr-work && cd rbr-work

# Create the environment. uv fetches Python 3.13 if you don't have it.
uv venv --python 3.13

Activate it — you do this in every new terminal session, and the command differs by platform:

# macOS / Linux
source .venv/bin/activate
# Windows PowerShell
.venv\Scripts\Activate.ps1

Then install into it and start Jupyter:

uv pip install numpy pandas matplotlib jupyter

jupyter notebook

With conda, it’s a named environment stored centrally instead:

conda create -n datasci python=3.13 numpy pandas matplotlib jupyter

# Activate it - again, in every new terminal session
conda activate datasci

jupyter notebook

The conda version takes a few minutes, because conda is resolving a consistent set of versions across everything you asked for and everything those packages depend on in turn. uv does the same job in well under a minute the first time, and in a few seconds after that, once the packages are in its local cache.

NoteWindows: “running scripts is disabled on this system”

If Activate.ps1 fails with that message, PowerShell is refusing to run local scripts. Reproducible Environments has the one-line fix.

Later chapters refer back to this environment as the one you made here — .venv under uv, datasci under conda. Reproducible Environments explains why one environment per project beats one environment for everything, and why the shared scratchpad you’ve just built is a pattern to grow out of.

This opens a web browser where you can create and work with notebooks. Let’s create a simple notebook to verify everything works:

  1. Click “New” → “Python 3”
  2. In the first cell, type:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# Create some sample data
data = pd.DataFrame({
    'x': range(1, 11),
    'y': np.random.randn(10)
})

# Create a simple plot
plt.figure(figsize=(8, 4))
plt.plot(data['x'], data['y'], marker='o')
plt.title('Sample Plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.grid(True)
plt.show()

print("Python environment is working correctly!")
  1. Press Shift+Enter to run the cell

If you see a plot and the success message, your Python setup is working.

4.1.3 Installing Additional Packages

With the environment activated:

uv pip install package_name      # uv
conda install package_name       # conda

Inside a conda environment you can also use pip for anything not packaged for conda, though mixing the two in one environment is a known way to end up with a broken environment. Install what you can with conda first, then pip for the remainder, and avoid alternating.

The case for reaching across to conda is narrower than it used to be. Most of the scientific stack now ships prebuilt wheels that uv installs without a compiler. Where conda still earns its place is packages wrapping non-Python system libraries — GDAL and PROJ for geospatial work, CUDA builds of PyTorch, much of bioinformatics — because something has to install those libraries too, and conda does.

4.2 Setting Up R

R was built for statistical computing rather than adapted to it, and it shows in small places: model objects that print something useful without being asked, missing values handled as a first-class idea, and CRAN packages written by the statisticians who developed the methods in them. The “Python or R?” section at the end of this chapter goes into when to reach for which.

4.2.1 Installing R

Let’s install both R itself and RStudio, a popular integrated development environment for R.

4.2.1.1 Installing Base R

  1. Visit the Comprehensive R Archive Network (CRAN)
  2. Click on the link for your operating system
  3. Follow the installation instructions

4.2.1.2 Installing RStudio Desktop

RStudio provides a user-friendly interface for working with R.

  1. Visit the Posit RStudio download page (RStudio’s parent company rebranded to Posit in 2022)
  2. Download the free RStudio Desktop version for your operating system
  3. Run the installer and follow the prompts

Think of R as the engine and RStudio as the dashboard that makes it easier to control that engine. You could use R without RStudio, but RStudio makes many tasks more convenient.

4.2.1.3 Verifying Installation

Open RStudio and enter this command in the console (lower-left pane):

R.version.string

RStudio also prints the same information unprompted at the start of every new session, so you may already see it above your cursor. It should look something like this:

R version 4.6.1 (2026-06-24 ucrt) -- "Happy Hop" Copyright (C) 2026 The R Foundation for Statistical Computing Platform: x86_64-w64-mingw32/x64

Your version number and codename will differ — R releases a new minor version each April and patches through the year. The ucrt and Platform lines only appear on Windows.

4.2.2 The R Packages to Start With

Five packages cover most of what the rest of this book does in R:

install.packages(c("tidyverse", "rmarkdown", "shiny", "knitr", "plotly"))

This installs:

  • tidyverse: A collection of packages for data manipulation and visualisation
  • rmarkdown: For creating documents that mix code and text
  • shiny: For building interactive web applications
  • knitr: For dynamic report generation
  • plotly: For interactive visualisations

The tidyverse is the one to learn first. It replaces most of base R’s data manipulation with a consistent set of verbs, and the other four assume you have it.

4.2.3 Creating Your First R Script

Verify the setup with a short script:

  1. In RStudio, go to File → New File → R Script
  2. Enter the following code:
# Load libraries
library(tidyverse)

# Create sample data
data <- tibble(
  x = 1:10,
  y = rnorm(10)
)

# Create a plot with ggplot2
ggplot(data, aes(x = x, y = y)) +
  geom_point() +
  geom_line() +
  labs(title = "Sample Plot in R",
       x = "X-axis",
       y = "Y-axis") +
  theme_minimal()

print("R environment is working correctly!")
  1. Click the “Run” button or press Ctrl+Enter (Cmd+Enter on Mac) to execute the code

If you see a plot in the lower-right pane and the success message in the console, your R setup is working.

4.2.4 Understanding R Packages

Unlike Python, where conda or pip manage packages, R has its own built-in package management system accessed through functions like install.packages() and library().

There are thousands of R packages available on CRAN, with more on Bioconductor (for bioinformatics) and GitHub. To install a package from GitHub, you first need the devtools package:

install.packages("devtools")
devtools::install_github("username/package")

Think of CRAN as the official app store for R packages, while GitHub is like getting apps directly from developers. Both are useful, but packages on CRAN have gone through more quality checks.

4.3 Python or R?

The question comes up constantly and has a boring answer: both are good, the differences that once mattered mostly don’t any more, and the deciding factor is almost always what the people around you use.

Where genuine differences remain:

  • R is stronger for statistical modelling and for publication-quality graphics. The tidyverse is a more coherent data-manipulation vocabulary than pandas, and ggplot2 has no true equal in Python. If your work is econometrics, biostatistics, or survey analysis, R’s package ecosystem is deeper.
  • Python is stronger everywhere the analysis has to connect to something else — a web application, a production pipeline, a machine learning framework, a cloud service. If your output is a system rather than a paper, Python is the shorter path.

Both are covered throughout this book because most working analysts eventually use both. Quarto renders either. Git doesn’t care. The environment and deployment chapters apply to both with minor syntax differences.

If you have no constraint and no preference: learn Python first, because more of the infrastructure in this book is Python-native, then pick up R when you meet a statistical problem it’s better at.

4.4 Conclusion

By the end of this chapter you should have:

  • Python installed, with uv --version working (or python --version and conda --version if you took the Miniforge route)
  • A working environment containing numpy, pandas, matplotlib, and Jupyter, which later chapters assume — a .venv if you took the uv route, an environment named datasci if you took conda
  • R and RStudio installed, with R.version.string reporting a current version
  • A Jupyter notebook that runs a cell and produces a plot
  • An R script that loads ggplot2 and produces a plot
  • Read the Reproducible Environments chapter before installing much else

The next chapter covers the editor you’ll work in and the version control that everything after it assumes.