liveBook · Manning

Tally() function

As explained in Statistics Slam Dunk

The tally() function from dplyr counts rows in a tabular object, optionally producing counts within established groups.

`tally()` counts rows in a tabular result. Used after `group_by()`, it returns one count for each established group; used after `filter()`, it returns the number of rows that remain. The output is a tibble with the count in `n`. section 8.4 section 19.3.1

The practical question is often simple: how many observations fit each category or condition? First narrow or prepare the data, then define groups when category-level counts are needed, and finish with `tally()`. Counts can check data quality, establish a benchmark, or supply probabilities for later analysis. section 8.4 section 9.3 section 3.8

Count NBA play-by-play event types

Group play-by-play rows by `event_type`, then tally them. The resulting tibble reveals 39 ejections, 101,684 missed shots, 112,803 rebounds, 86,633 made shots, and 790 rows with a missing event type. Such totals make patterns visible and expose uncategorized records worth investigating. `pbp %>% group_by(event_type) %>% tally()` section 8.4

Count outcomes after a tied halftime

After retaining games tied at halftime and removing tied third or fourth quarters, group rows by combinations of quarter winners and final winner. `tally()` counts each feasible path: home team wins both remaining quarters and the game (`HHH`) occurs 18 times, while `HRR` occurs 6 times. section 6.4.6 section 6.4.6

Common analytical uses include:

  • Count filtered records, such as 1,172 total-team records before resolving duplicate player-season entries. section 19.3.1
  • Count grouped wins to establish a home-versus-away benchmark: 4,224 home wins and 2,967 away wins. section 9.3
  • Count filtered draft-pick outcome segments and divide by the segment total to form probabilities for expected-value analysis. section 3.8

How Statistics Slam Dunk covers it

How deep it goes
Demonstrates `tally()` in executable pipelines and interprets its output, without detailing its implementation.
Examples
Uses NBA event types, home and away wins, tied-halftime results, draft outcomes, and duplicate total-team records.
What it assumes
Uses R pipes, dplyr data frames, `filter()`, and `group_by()` in the counting workflows.
What you can do after
Apply it via dplyr to count observations overall or within groups and interpret the resulting tibble.
How it connects
Connects `tally()` with `group_by()`, `filter()`, `summarize()`, `distinct()`, factors, and expected value.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Statistics Slam Dunk. The section links point to the parts of the book it draws on.