Appendix J — R for Cricket Analytics

This book is written in Python, and every number in it comes from Python code run against the book's data snapshot. But a large share of the people who do sports analytics for a living work in R — the language of Analyzing Baseball Data with R, of Hadley Wickham's R for Data Science, and of two long-running community cricket packages. If you already think in dplyr and ggplot2, you should not have to learn pandas before you can ask a cricket question. If you are a Python reader, a working knowledge of R doubles the number of analysts whose code you can read.

This appendix is the R reader's companion to the book. It covers:

  1. installing R and RStudio, and the handful of packages the book's R snippets use;
  2. reading the book's own Parquet files in R (and a CSV fallback);
  3. the book's standard batting and bowling tables written in dplyr — the same definitions, to the decimal, as toolkit/cricdata.py;
  4. the three community packages you will meet — cricketr, yorkr and cricketdata — and what each actually does;
  5. a Python ↔ R translation table;
  6. when to use which language;
  7. a list of every 🔷 R corner in the chapters, with links.

⚠️ Common pitfall — two languages, two sets of numbers. The fastest way to lose an argument is to compute "strike rate" in R one way and in Python another and then wonder why your numbers differ from the book's. They will differ if the definitions differ: whether wides count as balls faced, whether a non-striker run-out counts against the batter, whether wides and no-balls are charged to the bowler. Section J.3 writes the book's definitions in R exactly, so the numbers match.

A note on how this appendix was checked

R is not part of this book's build environment, so the R code in this appendix is not run in this book's build. That is the same rule as the 🔷 R corners in the chapters. To keep the R honest anyway, the appendix ships two companion files:

  • appendices/code/j_cricket_summaries.R — the complete R script (the code in J.3 and J.5), ready to run with Rscript once you have installed the packages below;
  • appendices/code/j_r_parity.py — a Python script that (a) transliterates the dplyr pipelines below line by line into pandas (filter → boolean mask, group_by + summarise → groupby().agg(), left_join → merge(how="left"), coalesce → fillna) and checks that the result agrees with the toolkit's batting_summary and bowling_summary in every cell, and (b) prints the reference numbers your R output should reproduce.

The parity run, pasted exactly:

1. Parity: dplyr transliteration v toolkit, IPL 2008-2026
  batting, by batter                 rows toolkit   738  transliteration   738  cells compared   8,856  identical: True
  batting, by batter x phase         rows toolkit  1617  transliteration  1617  cells compared  19,404  identical: True
  bowling, by bowler                 rows toolkit   577  transliteration   577  cells compared   6,924  identical: True
  bowling, by bowler x phase         rows toolkit  1502  transliteration  1502  cells compared  18,024  identical: True

So the logic of the R pipelines reproduces the book's definitions on every IPL batter and bowler, overall and by phase. What the parity check cannot catch is an R-specific slip (a typo, a package-version difference). If you run the R script and a number disagrees with the reference output in J.3, trust the Python and look for the slip.


J.1 Installing R, RStudio and the packages

The cricket question: can a fan in Dhaka with an old laptop and slow internet run the book's analysis in R? Yes — R, RStudio Desktop and every package used here are free and run on Windows, macOS and Linux.

  1. Install R from CRAN, the Comprehensive R Archive Network (https://cran.r-project.org). Pick your operating system and the "base" distribution. On Windows this is a normal installer; accept the defaults.
  2. Install RStudio Desktop (free, from Posit, the company that maintains it). It is an editor with a console, a plot pane and a data viewer. You do not need it — Rscript from a terminal runs any .R file — but most R users work in it, and the book's R snippets are written to be pasted into its console.
  3. Install the packages. In the R console:
install.packages(c("arrow", "dplyr", "tidyr", "ggplot2"))   # the core four
install.packages(c("survival", "mclust", "lpSolve"))         # used by single R corners
install.packages(c("cricketdata", "yorkr", "cricketr"))      # community cricket packages (J.4)

On Windows and macOS, CRAN supplies pre-built binaries, so nothing needs compiling. arrow is the largest download (tens of megabytes) — on a slow connection, install it once and keep it.

Package What the book uses it for
arrow read_parquet() — read the book's data/processed/*.parquet files directly
dplyr filter, group, summarise, join — the R equivalent of the pandas you learn in Chapter 3
tidyr pivot_longer() / pivot_wider() — reshape tables (pandas melt / pivot)
ggplot2 charts — the grammar-of-graphics equivalent of matplotlib
survival Kaplan–Meier and Cox models (Chapter 10)
mclust Gaussian-mixture clustering (Chapter 15)
lpSolve the integer programme that picks an XI (Chapter 21)
jsonlite reading a raw Cricsheet JSON file (Chapter 2) — installed with install.packages("jsonlite")

🔍 Why this works — the native pipe. The book's R snippets use |>, the pipe built into R since version 4.1. Older code (and some R corners) uses %>% from the magrittr package, which dplyr loads for you. For everything in this book the two are interchangeable: x |> f(y) means f(x, y). If your R is older than 4.1, replace |> with %>%.


J.2 Getting the book's data into R

Reading Parquet with arrow

The toolkit (toolkit/cricdata.py) downloads Cricsheet's JSON archives once and writes two Parquet files per competition into data/processed/: <code>_deliveries.parquet (one row per delivery) and <code>_matches.parquet (one row per match). Parquet is a column-oriented format that both languages read natively, so R can use the same files the Python chapters use — no re-download, no re-parsing, the same rows.

library(arrow)
library(dplyr)

setwd("C:/books/cricket-analytics")            # wherever your copy of the book lives
balls <- read_parquet("data/processed/ipl_deliveries.parquet")
games <- read_parquet("data/processed/ipl_matches.parquet")

dim(balls)          # rows, columns
glimpse(balls)      # column names and types

Everything about the columns is in Appendix B; the ones the R code below relies on are:

Column Meaning R type after read_parquet
match_id Cricsheet match id, e.g. "936157" character
season Cricsheet season label (a string: "2026", "2007/08" = IPL 2008, "2020/21" = IPL 2020) character
start_date match start date date-time
innings, over, ball_in_over innings number; over (1-based); ball within the over integer
super_over delivery belongs to a super over logical
batter, non_striker, bowler, player_out Cricsheet name spellings character
batter_id, non_striker_id, bowler_id, player_out_id Cricsheet registry ids — unique per person character
runs_batter, runs_extras, runs_total runs off the bat, extras, total on the delivery integer
wides, noballs, byes, legbyes, penalty extras by kind (0 when none) integer
is_legal, is_four, is_six, is_wicket flags logical
wicket_kind "caught", "bowled", "run out", … (NA when no wicket) character
phase "powerplay" / "middle" / "death" (T20, ODI, Hundred); "none" in Tests character

⚠️ Common pitfall — names are not people. Cricsheet spellings collide: there are three different "Rashid Khan"s in men's T20Is, and 70 names are shared by two or more people within single competitions. Inside one competition the famous names in this appendix are safe, but when you aggregate a named player across competitions, group by batter_id / bowler_id, not by name. The Python helper cricdata.only_player() does this for you; in R, find the id first:

r balls |> filter(bowler == "Rashid Khan") |> count(bowler_id, sort = TRUE)

⚠️ Common pitfall — Afghanistan's internationals are missing. Cricsheet withholds Afghanistan men's Tests, ODIs and T20Is by policy, so Afghan players appear in this data only through franchise leagues. That is true whichever language reads the files.

The CSV fallback

If arrow will not install (an old operating system, a locked-down work laptop), export CSV from Python and read it with base R or readr. Write the logical columns as 0/1 so that every reader parses them the same way:

# Python: export one season to CSV (run from the book root)
import sys; sys.path.insert(0, "toolkit")
from cricdata import load_deliveries
ipl = load_deliveries("ipl")
i26 = ipl[ipl["season"] == "2026"].copy()
flags = [c for c in i26.columns if i26[c].dtype == bool]
i26[flags] = i26[flags].astype(int)
i26.to_csv("ipl_2026_deliveries.csv", index=False)
# R: read it back and restore the logical columns
balls <- read.csv("ipl_2026_deliveries.csv", colClasses = c(match_id = "character", season = "character"))
flags <- c("super_over", "is_legal", "is_four", "is_six", "is_wicket", "declared")
balls[flags] <- lapply(balls[flags], as.logical)

j_r_parity.py runs the Python half of this round trip and checks it:

3. CSV fallback: IPL 2026 deliveries -> CSV -> back
  rows 17,527, columns 42, CSV size 4.2 MB (Parquet for all of IPL 2008-2026: 2.3 MB)
  logical columns written as 0/1: super_over, is_legal, is_four, is_six, is_wicket, declared
  batting_summary on the re-read CSV matches the Parquet original: True

Note the sizes: one IPL season as CSV (4.2 MB) is already larger than all nineteen IPL seasons as Parquet (2.3 MB). On a slow connection or a small disk, that is a good reason to get arrow working. Two further CSV traps: keep match_id and season as character (otherwise read.csv turns ids such as "936157" and a single-season file's "2026" into numbers, and a left_join with a table that stores them as text — the Parquet matches table, for one — fails on the type mismatch), and remember that an empty wicket_kind reads as "" in base R but NA in arrow — wicket_kind %in% c(...) treats both correctly.


J.3 The book's batting and bowling tables in dplyr

The cricket question: what are a batter's runs, balls, average and strike rate — exactly as the book defines them?

The definitions (from Chapter 4 and Chapter 8, collected in Appendix C):

📐 Definition — the book's batting table. Balls faced = deliveries as striker, excluding wides (no-balls do count). Runs = runs off the bat. Outs = dismissals of that player, including run-outs at the non-striker's end, excluding retired hurt and retired not out. Innings = distinct (match, innings) in which the player batted as striker or non-striker. Average = runs / outs. Strike rate = 100 × runs / balls. Dot % = balls faced with nothing off the bat / balls faced. Boundary ball % = (4s + 6s) / balls faced. Boundary run % = (4 × 4s + 6 × 6s) / runs. Super-over deliveries are excluded.

📐 Definition — the book's bowling table. Balls = legal deliveries. Runs conceded = total runs − byes − leg-byes − penalty runs (wides and no-balls are charged to the bowler). Wickets = bowled, caught, caught and bowled, lbw, stumped, hit wicket. Economy = 6 × runs / balls; average = runs / wickets; strike rate = balls / wickets; dot % = legal balls conceding nothing to the bowler; boundary % = legal balls hit for four or six.

Batting

not_dismissal <- c("retired hurt", "retired not out")

batting_summary <- function(balls, by = "batter") {
  b <- balls |> filter(!super_over)
  faced <- b |>
    filter(wides == 0) |>                                   # balls faced exclude wides only
    group_by(across(all_of(by))) |>
    summarise(runs = sum(runs_batter), balls = n(),
              fours = sum(is_four), sixes = sum(is_six),
              dots = sum(runs_batter == 0), .groups = "drop")
  outs <- b |>
    filter(is_wicket, !wicket_kind %in% not_dismissal) |>   # incl. non-striker run-outs
    mutate(batter = player_out) |>
    group_by(across(all_of(by))) |>
    summarise(outs = n(), .groups = "drop")
  rest <- setdiff(by, "batter")
  inns <- bind_rows(
      b |> select(match_id, innings, all_of(by)),
      b |> select(match_id, innings, all_of(rest), batter = non_striker)) |>
    distinct() |>
    group_by(across(all_of(by))) |>
    summarise(innings = n(), .groups = "drop")
  faced |>
    left_join(outs, by = by) |>
    left_join(inns, by = by) |>
    mutate(outs = coalesce(outs, 0L),
           innings = coalesce(innings, 0L),
           average = round(if_else(outs > 0, runs / outs, NA_real_), 2),
           strike_rate = round(100 * runs / balls, 2),
           dot_pct = round(100 * dots / balls, 2),
           boundary_ball_pct = round(100 * (fours + sixes) / balls, 2),
           boundary_run_pct = round(if_else(runs > 0, 100 * (4 * fours + 6 * sixes) / runs, NA_real_), 2)) |>
    arrange(desc(runs))
}

Four details carry the definitions, and each is a place where a quick R version usually goes wrong:

  1. filter(wides == 0) before counting balls. A wide is not a ball faced. A no-ball is — the batter could hit it — so it stays.
  2. mutate(batter = player_out) before counting outs. The dismissed player is not always the striker: a run-out at the non-striker's end belongs to the non-striker. Counting is_wicket on the striker's rows would hand that dismissal to the wrong person.
  3. The innings count stacks striker and non-striker rows. A batter run out without facing a ball still batted an innings. bind_rows of the two roles, then distinct(), then count.
  4. left_join, then coalesce(…, 0L). A batter who was never out has no row in outs; the join leaves NA, which becomes 0, and the average becomes NA (undefined), never infinity.

The by argument works exactly like the toolkit's: by = c("batter", "phase") gives phase profiles, by = c("batter", "season") gives season tables.

Bowling

bowler_kinds <- c("bowled", "caught", "lbw", "stumped", "caught and bowled", "hit wicket")

bowling_summary <- function(balls, by = "bowler") {
  balls |>
    filter(!super_over) |>
    mutate(rc  = runs_total - byes - legbyes - penalty,      # wides and no-balls ARE charged
           wkt = wicket_kind %in% bowler_kinds) |>           # NA %in% x is FALSE in R
    group_by(across(all_of(by))) |>
    summarise(balls = sum(is_legal), runs = sum(rc), wickets = sum(wkt),
              dots = sum(is_legal & rc == 0),
              boundaries = sum(is_legal & (is_four | is_six)),
              matches = n_distinct(match_id), .groups = "drop") |>
    filter(balls > 0) |>
    mutate(overs = balls %/% 6 + (balls %% 6) / 10,
           economy = round(6 * runs / balls, 2),
           average = round(if_else(wickets > 0, runs / wickets, NA_real_), 2),
           strike_rate = round(if_else(wickets > 0, balls / wickets, NA_real_), 2),
           dot_pct = round(100 * dots / balls, 2),
           boundary_pct = round(100 * boundaries / balls, 2)) |>
    arrange(desc(wickets))
}

The overs column uses cricket notation: 64.4 means 64 overs and 4 balls (388 balls), not 64.4 decimal overs. Compute rates from balls, never from overs.

🔍 Why this works — NA and %in%. In R, NA == "caught" is NA, and sum() of a vector containing NA is NA — one missing value poisons the whole total. %in% is different: NA %in% c("caught") is FALSE. Writing wkt = wicket_kind %in% bowler_kinds therefore gives a clean TRUE/FALSE on every delivery, including the vast majority where wicket_kind is missing. The pandas equivalent, isin, behaves the same way.

Reference output

Run on IPL 2026 (filter(season == "2026")), your R should print the same numbers as the toolkit. From j_r_parity.py:

IPL 2026 batting, top five by runs (batting_summary):
                 runs  balls  outs  innings  average  strike_rate  dot_pct  boundary_ball_pct  boundary_run_pct
batter                                                                                                         
V Suryavanshi     776    327    16       16    48.50       237.31    33.03              41.28             88.14
Shubman Gill      732    449    16       16    45.75       163.03    30.96              23.83             67.49
B Sai Sudharsan   722    457    16       17    45.12       157.99    31.07              22.98             66.48
V Kohli           675    407    12       16    56.25       165.85    26.04              24.08             65.48
H Klaasen         624    390    13       15    48.00       160.00    26.92              20.26             60.58

IPL 2026 bowling, top five by wickets (bowling_summary):
             balls  overs  runs  wickets  economy  average  strike_rate  dot_pct  boundary_pct
bowler                                                                                        
K Rabada       388   64.4   626       29     9.68    21.59        13.38    44.33         25.77
B Kumar        378   63.0   501       28     7.95    17.89        13.50    40.21         16.93
JC Archer      360   60.0   559       25     9.32    22.36        14.40    43.89         25.28
A Kamboj       302   50.2   530       21    10.53    25.24        14.38    38.74         27.15
Rashid Khan    341   56.5   516       21     9.08    24.57        16.24    34.31         18.18

And the phase question that opens the book (Chapter 1): career IPL strike rate by phase, 2008–2026.

batting_summary(filter(ipl, batter %in% c("V Kohli", "SA Yadav")), by = c("batter", "phase")) |>
  select(batter, phase, strike_rate) |>
  pivot_wider(names_from = phase, values_from = strike_rate)
IPL career strike rate by phase, 2008-2026 (the Chapter 1 R corner):
phase     powerplay  middle   death
batter                             
SA Yadav     141.05  144.14  178.21
V Kohli      129.55  125.80  188.38

📋 Try it — Build this metric. Using batting_summary(..., by = c("batter", "phase")), find the IPL batter with the highest death-overs strike rate among those with at least 300 death-overs balls, 2008–2026. Then add season to by and check whether that batter's best death season had more than 100 balls.

Answer

r ipl |> batting_summary(by = c("batter", "phase")) |> filter(phase == "death", balls >= 300) |> arrange(desc(strike_rate)) |> head(5) Then take the top name, filter(batter == "<name>", phase == "death") on batting_summary(ipl, by = c("batter", "phase", "season")), and sort by strike_rate. The point of the exercise is the second step: a career rate over 300+ balls is a reasonably stable number; a single death-overs season is often 40–80 balls, and Chapter 6 found that an IPL strike rate needs roughly 98 balls before it is even half signal and half noise. Report the balls next to every rate.


J.4 The community packages: cricketr, yorkr and cricketdata

Three R packages on CRAN are aimed squarely at cricket. They overlap with this book in places and differ from it in important ways, so it is worth knowing exactly what each does. Everything below was checked against each package's CRAN page and reference manual in November 2026; versions change, so check packageVersion("<name>") and the package's own documentation before relying on a detail.

cricketr (Tinniam V. Ganesh)

  • What it is: "Analyze Cricketers and Cricket Teams Based on ESPN Cricinfo Statsguru" — CRAN version 0.0.26 (2021).
  • Data source: ESPNcricinfo Statsguru, not Cricsheet. Its getPlayerData() fetches a player's innings-by-innings record from Statsguru and saves it to a local CSV; most analysis functions then take that file. Signature from the manual: getPlayerData(profile, opposition = "", host = "", dir = "./data", file = "player001.csv", type = "batting", homeOrAway = c(1, 2, 3), result = c(1, 2, 4)), where profile is the player's Cricinfo profile number. Variants for other formats include getPlayerDataOD() and getPlayerDataTT().
  • What it computes: innings-level plots and summaries — e.g. batsmanRunsFreqPerf(file, name), batsman4s(file, name), batsmanPerfBoxHist(file, name), batsmanMovingAverage, batsmanCumulativeAverageRuns, batsmanPerfForecast, bowlerWktsFreqPercent(file, name), bowlerMovingAverage, checkBatsmanInForm, plus team functions such as getTeamData and teamWinLossStatusVsOpposition. It also ships small example datasets named after players (e.g. kohli, tendulkar, warne).
  • How it relates to this book: cricketr works at the innings level (one row per innings from a scorecard), not the ball level. That makes it a good tool for career-arc questions — form, moving averages, home/away, the "is this player in form?" question — and it cannot answer phase, matchup, partnership-tempo or win-probability questions, which need ball-by-ball data. Because Statsguru and Cricsheet are compiled separately, cricketr's career numbers can also differ by a run or a match from the book's for older matches.

yorkr (Tinniam V. Ganesh)

  • What it is: "Analyze Cricket Performances Based on Data from Cricsheet" — CRAN version 0.0.42 (2024). The CRAN description says it works from Cricsheet's match data in YAML form.
  • Workflow: convert a folder of Cricsheet match files into R data frames — convertAllYaml2RDataframes(sourceDir = ".", targetDirMen = ".", targetDirWomen = ".") (and a T20 variant, convertAllYaml2RDataframesT20) — then save matches between teams (saveAllMatchesBetweenTeams, league-specific versions such as saveAllMatchesBetween2IPLTeams) and extract player tables (getBatsmanDetails(team, name, dir = "."), getBowlerWicketDetails, and league helpers such as getIPLBattingDetails / getIPLBowlingDetails).
  • What it computes: a very large catalogue of match, team and player charts and tables. Match-level: matchWormGraph, teamBattingScorecardMatch, teamBowlingScorecardMatch, teamBatsmenPartnershipMatch, teamBatsmenVsBowlersMatch, teamRunsSRPlotMatch (with powerplay, middle-overs and death-overs versions). Player-level: batsmanRunsVsStrikeRate(df, name, dateRange, staticIntv = 1), batsmanDismissals, batsmanFoursSixes, batsmanVsBowlerPerf, bowlerMovingAverage, bowlerVsBatsmanPerf. Rankings: rankT20Batsmen, rankT20Bowlers, rankODIBatsmen, rankODIBowlers. It also includes win-probability functions (winProbabilityLR, winProbabilityRF, winProbabilityDL, batsmanWinProbLR, bowlerWinProbLR and others).
  • How it relates to this book: yorkr is the closest R relative of the book's toolkit and of Crease — ball-by-ball, Cricsheet-based, with worms, partnerships, matchups and phase splits. Two cautions. First, its definitions are its own: before comparing a yorkr strike rate or economy rate with the book's, check how it treats wides, no-balls, byes and non-striker run-outs, because a mismatch there produces small, confusing differences. Second, its conversion step is built around Cricsheet's YAML files; check Cricsheet's downloads page for which formats are currently offered before planning a workflow around them. The book's toolkit reads Cricsheet's JSON archives.

cricketdata (Rob Hyndman and co-authors)

  • What it is: "International Cricket Data" — CRAN version 0.3.0 (2025); authors Rob Hyndman, Charles Gray, Sayani Gupta, Timothy Hyndman, Hassan Rafique and Jacquie Tran (with contributors). Data on international and other major cricket from ESPNcricinfo and Cricsheet, returned as tibbles.
  • Functions (the full documented list): fetch_cricsheet(), fetch_cricinfo(), fetch_player_data(), fetch_player_meta(), find_player_id(), update_player_meta(), plus the datasets cricsheet_codes and player_meta.
  • fetch_cricsheet(type = c("bbb", "match", "player"), gender = c("female", "male"), competition = "tests") — ball-by-ball ("bbb"), match information or player information from Cricsheet. Competition codes are the package's own; print cricsheet_codes to see them (the package's vignette uses competition = "wbbl" for the Women's Big Bash League).
  • fetch_cricinfo(matchtype = c("test", "odi", "t20"), sex = c("men", "women"), activity = c("batting", "bowling", "fielding"), type = c("career", "innings"), country = NULL) — career or innings-by-innings tables from Cricinfo.
  • fetch_player_data(playerid, matchtype, activity) — one row per innings for one player, by Cricinfo player id; find_player_id("<name>") looks the id up.
  • Column names: the ball-by-ball tibble follows Cricsheet's CSV conventions — the package's own vignette works with match_id, season, start_date, innings, ball, batting_team, bowling_team, striker, runs_off_bat, extras and wicket_type.
  • How it relates to this book: cricketdata is the quickest way to get Cricsheet or Cricinfo data into R without Python. If you use it, map its columns to the book's before reusing the code in J.3:
Book (toolkit Parquet) Cricsheet ball-by-ball CSV (as used by cricketdata) Note
batter striker
non_striker, bowler non_striker, bowler same
runs_batter runs_off_bat
runs_extras extras
runs_total runs_off_bat + extras compute it
wides, noballs, byes, legbyes, penalty same names NA where the book has 0 — use coalesce(x, 0)
over, ball_in_over ball (e.g. 23.5 = 5th ball of the 24th over) the book's over is 1-based: over = floor(ball) + 1
wicket_kind, player_out wicket_type, player_dismissed
is_legal — is.na(wides) & is.na(noballs)
is_four, is_six — not identical to runs_off_bat == 4 (an all-run four is not a boundary); the CSV's non_boundary flag helps
phase — derive from over (T20: 1–6, 7–15, 16–20)
super_over — check how super overs are numbered in the innings column before filtering

Sources for this section: the CRAN pages and reference manuals of cricketr, yorkr and cricketdata; the cricketdata Cricsheet vignette; Cricsheet's description of its ball-by-ball CSV format. Further notes are in Chapter 2's further reading.

🏏 Eye test: a package that draws a worm in one line is a gift when you need a chart for a team meeting in ten minutes. But the coach in the room will ask "how many balls was that?" and "does that count the run-out?" — and you need to be able to answer from the definition, not from the package's defaults. Use the packages to move fast; use J.3 when the number has to be defended.


J.5 Python ↔ R translation table

Every row is a pair of idioms that do the same job on the book's deliveries table (balls in both languages).

Data wrangling

Task Python (pandas) R (dplyr / tidyr)
Read Parquet pd.read_parquet(path) or load_deliveries("ipl") arrow::read_parquet(path)
Look at it balls.head(), balls.info() head(balls), glimpse(balls)
Filter rows balls[balls["wides"] == 0] or balls.query("wides == 0") filter(balls, wides == 0)
Several conditions balls[(balls["phase"] == "death") & ~balls["super_over"]] filter(balls, phase == "death", !super_over)
In a set balls["batter"].isin(["V Kohli", "SA Yadav"]) batter %in% c("V Kohli", "SA Yadav")
New column balls.assign(rc=balls["runs_total"] - balls["byes"]) mutate(balls, rc = runs_total - byes)
Choose columns balls[["batter", "runs_batter"]] select(balls, batter, runs_batter)
Rename .rename(columns={"non_striker": "batter"}) rename(batter = non_striker)
Group and summarise .groupby("batter").agg(runs=("runs_batter", "sum"), balls=("runs_batter", "size")) group_by(batter) \|> summarise(runs = sum(runs_batter), balls = n())
Count rows per group .groupby("batter").size() or .value_counts() count(batter)
Distinct count .nunique() n_distinct()
Sort .sort_values("runs", ascending=False) arrange(desc(runs))
Top n .head(10) / .nlargest(10, "runs") head(10) / slice_max(runs, n = 10)
Left join a.merge(b, on="match_id", how="left") left_join(a, b, by = "match_id")
Stack tables pd.concat([a, b]) bind_rows(a, b)
Drop duplicate rows .drop_duplicates() distinct()
Missing → 0 .fillna(0) coalesce(x, 0) / replace_na()
Long → wide .pivot(index=..., columns=..., values=...) / .unstack() pivot_wider(names_from = ..., values_from = ...)
Wide → long .melt(...) pivot_longer(...)
Cumulative sum within group .groupby("innings")["runs_total"].cumsum() group_by(innings) \|> mutate(score = cumsum(runs_total))
Lag .shift(1) lag(x)
Running count within group .groupby(key).cumcount() row_number() - 1 after group_by
Conditional value np.where(cond, a, b) if_else(cond, a, b) / case_when(...)
Bin a number pd.cut(x, bins) cut(x, breaks)
Year from a date balls["start_date"].dt.year lubridate::year(start_date) or as.integer(format(start_date, "%Y"))

Statistics, models and charts

Task Python R
Correlation df["average"].corr(df["strike_rate"]) cor(df$average, df$strike_rate)
Bootstrap interval (innings resampling, Chapter 6) numpy.random.default_rng(6).integers(...) set.seed(6); sample(n, replace = TRUE)
Beta–binomial shrinkage crease.uncertainty.shrink_beta (x + a) / (n + a + b) in mutate()
Logistic regression statsmodels.formula.api.logit("won ~ x", df) / sklearn.linear_model.LogisticRegression glm(won ~ x, data = df, family = binomial)
Linear regression statsmodels.formula.api.ols("y ~ x", df) lm(y ~ x, data = df)
Kaplan–Meier, Cox (Chapter 10) lifelines.KaplanMeierFitter, CoxPHFitter survival::survfit(Surv(balls, out) ~ batter), coxph()
k-means / Gaussian mixture (Chapter 15) sklearn.cluster.KMeans, sklearn.mixture.GaussianMixture kmeans(), mclust::Mclust()
Integer programme (Chapter 21) scipy.optimize.milp lpSolve::lp(..., all.bin = TRUE)
Gradient boosting xgboost.XGBClassifier xgboost::xgboost()
Networks (Chapter 12) networkx igraph
Bar chart ax.bar(x, y) ggplot(df, aes(x, y)) + geom_col()
Line / worm ax.plot(x, y) geom_line() / geom_step()
Scatter ax.scatter(x, y) geom_point()
Heat map crease.charts.heatmap(table) geom_tile() + geom_text()
Small multiples crease.charts.small_multiples(n) facet_wrap(~ competition)
Save a figure charts.save(fig, "x.png") ggsave("x.png", width = 10, height = 4.6, dpi = 110)

⚠️ Common pitfall — indexing starts at 1 in R and 0 in Python. The book's over column is already 1-based (over 1 is the first over) in both languages, because it is data, not an index. But x[1] is the first element in R and the second in Python, and iloc[0] has no R twin other than x[1] or first(x). Off-by-one errors in "the last ball of the over" logic are the commonest bug when porting.

A chart in both languages

The Manhattan — runs per over with wickets marked — is the first chart in Chapter 7. In Python it is one call to the Crease chart module (see Appendix K, chart K-01):

from cricdata import load_deliveries
from crease import charts
m = charts.match_balls(load_deliveries("t20s_male"), "936157")
charts.save(charts.manhattan(m).figure, "manhattan.png")

In R, the same chart in the book's colours (team batting first blue #1f77b4, team batting second orange #ff7f0e, wickets as a red "X"):

t20i <- read_parquet("data/processed/t20s_male_deliveries.parquet")
overs <- t20i |>
  filter(match_id == "936157", !super_over) |>
  mutate(out = is_wicket & !wicket_kind %in% not_dismissal) |>
  group_by(innings, batting_team, over) |>
  summarise(runs = sum(runs_total), wkts = sum(out), .groups = "drop") |>
  mutate(x = over + if_else(innings == 1, -0.2, 0.2))         # side-by-side bars, by hand

p <- ggplot(overs, aes(x, runs, fill = batting_team)) +
  geom_col(width = 0.38) +
  geom_point(data = filter(overs, wkts > 0), aes(x, runs + 1.5),   # one X per over with wickets
             inherit.aes = FALSE, shape = 4, size = 2.5, stroke = 1.3, colour = "#d62728") +
  scale_fill_manual(values = c("South Africa" = "#1f77b4", "Sri Lanka" = "#ff7f0e")) +
  scale_x_continuous(breaks = 1:20) +
  labs(x = "Over", y = "Runs in the over", fill = NULL,
       title = "Manhattan — Newlands T20I, 25 Jan 2017") +
  theme_minimal(base_size = 11) +
  theme(legend.position = "top", panel.grid.major.x = element_blank())
ggsave("manhattan_r.png", p, width = 10, height = 4.6, dpi = 110)

The R version marks one X per over even when two wickets fell in it (over 16, Imran Tahir's two-run, two-wicket over); the Crease function stacks one X per wicket. Stacking them in ggplot2 means expanding the wicket rows (tidyr::uncount(wkts)) and offsetting each by its row number — a good first exercise in porting a design decision rather than a formula.


J.6 When to use which

Neither language is better at cricket. They are better at different parts of the job.

Situation Reach for Why
Following this book chapter by chapter, building Crease Python Every chapter's code, module and test is Python; the dashboard in Chapter 39 is Streamlit
A quick exploratory table, group-by-summarise, and a publication-quality chart R (dplyr + ggplot2) or Python — personal taste dplyr's verbs read like the question; ggplot2's facets make small multiples trivial
Statistical modelling with formula syntax, mixed models, survival, classical inference R has the deeper bench glm, survival, and decades of statistical packages; the output of summary() is what statisticians expect to read
Machine learning pipelines, gradient boosting at scale, deployment into a web app Python scikit-learn, xgboost and the web/dashboard ecosystem
Career-arc questions from official scorecard records (form, moving averages, home/away) R: cricketr Built for innings-level Statsguru data
Ball-by-ball match and player charts in a hurry R: yorkr, or Python: crease.charts Both draw worms, partnerships and phase splits; check yorkr's definitions against J.3
Getting Cricsheet data into R without Python at all R: cricketdata fetch_cricsheet() returns tibbles directly
Working with a club or franchise analyst team Whatever the team uses A shared language beats a better one

🔄 Check your understanding 1. Your R strike rate for a batter is 0.8 points lower than the book's. Name the single most likely definitional cause. 2. Why does batting_summary set batter = player_out before counting outs? 3. You want IPL strike rate by phase for 2008–2026 and also a "form" chart of a Test batter's last 30 innings from official records. Which R package suits each?

Answer

  1. Counting wides as balls faced (forgetting filter(wides == 0)) — it adds balls without runs off the bat, lowering strike rate. A second candidate is dropping no-balls from balls faced, which would raise it.
  2. Because the dismissed player is not always the striker: a run-out at the non-striker's end is the non-striker's dismissal. Counting outs on the striker's rows would charge it to the wrong batter.
  3. Phase strike rate needs ball-by-ball data — the book's Parquet files with batting_summary(by = c("batter", "phase")), or yorkr / cricketdata. An innings-level form chart from official records is what cricketr was built for.

J.7 The 🔷 R corners in the chapters

Nineteen chapters carry a short 🔷 R corner: an R version of one of the chapter's key computations, labelled "not run in this book's build". They assume the toolkit's column names (J.2) unless the snippet says otherwise. In order:

Chapter The R corner shows Packages
1 — Cricket's Moneyball Moment Kohli and Suryakumar's IPL strike rate by phase, read straight from Parquet arrow, dplyr
2 — Cricket Data Reading one raw Cricsheet JSON match file jsonlite
3 — Python and pandas for Cricket The IPL 2026 top-ten run-scorers table arrow, dplyr
4 — Why Traditional Statistics Lie Not-out diagnostics: average v runs per innings dplyr
5 — The Three Formats Format baselines (run rate, balls per wicket) across formats dplyr
6 — Statistical Thinking The innings bootstrap for a batting average base R
7 — Visualizing Cricket Strip plots of batting metrics (the honest alternative to a radar) dplyr, tidyr, ggplot2
8 — Beyond Batting Average Strike rate, dot % and boundary-ball % per format dplyr
9 — Batting Impact and Context The counting step of the WP v0 win-probability table dplyr
10 — Batting in Test Cricket Kaplan–Meier and Cox models of batting survival survival
11 — Batting Against Specific Bowlers The league-cell expectation for a batter–bowler-type matchup dplyr
12 — Batting Partnerships Numbering the stands in an innings dplyr
14 — Bowling Analytics A bowler's phase profile (economy, dot %, boundary %) dplyr
15 — Pitch Maps and Ball-Tracking k-means and Gaussian-mixture clustering of 🧪 simulated deliveries base R, mclust
16 — Bowling in Test Cricket Extracting bowling spells from an over-by-over table dplyr
17 — Fielding Analytics The fielder credit table from a semicolon-separated fielders column dplyr, tidyr
18 — Spin vs. Pace Strike rate against spin turning into and away from the bat dplyr
21 — Team Composition and Balance A toy XI-selection integer programme lpSolve
22 — Toss, Venue, and Conditions The toss-and-home logistic regression base R (glm)

Two habits make the R corners easier to use. First, start every session with the two functions from J.3 (source("appendices/code/j_cricket_summaries.R") loads them along with the examples; copy just the two functions into your own file if you prefer). Second, when an R corner says "assuming a data frame inns with columns …", build that data frame in R from the deliveries with the J.3 functions rather than exporting it from Python — it is the best practice you will get at reading the book in R.

🧩 Productive struggle. Chapter 12's R corner numbers the stands in an innings. Before reading it, try writing it yourself: a stand ends on the delivery on which any wicket falls (including retirements), and the next stand begins on the following delivery. Hint: within each (match_id, innings), sorted by delivery_seq, the stand number is one plus the cumulative count of wickets on all earlier deliveries — something like cumsum(lag(n_wickets_on_ball, default = 0)) + 1. Check your answer on Newlands 2017 (match 936157): Sri Lanka's third stand, Dhananjaya de Silva and Niroshan Dickwella, was worth 71 runs from 61 legal balls (Appendix K, chart K-04).


Summary

  • R reads the book's Parquet files directly with arrow::read_parquet(); a CSV export from Python, with logical columns written as 0/1, is the fallback.
  • The book's batting and bowling tables in dplyr are in J.3. Their logic is checked cell-for-cell against the toolkit by a pandas transliteration; the R itself is not run in this book's build, so check your output against the reference tables.
  • cricketr analyses innings-level ESPNcricinfo Statsguru data; yorkr analyses Cricsheet ball-by-ball match data with a large chart catalogue; cricketdata fetches Cricsheet and Cricinfo data straight into tibbles. Check any package's definitions before comparing its numbers with the book's.
  • Use whichever language your team uses. When a number has to be defended, use the definitions — not a package default.