liveBook · Manning

Pivot_longer() function

As explained in Statistics Slam Dunk

The pivot_longer() function from tidyr reshapes tabular data from wide format into long format by gathering multiple columns into key-value columns.

`pivot_longer()` from tidyr reshapes a data object from wide to long format: selected columns become rows. It needs the columns to collapse plus names for a new key column and a new value column. Use `cols` to select source columns, `names_to` for their former column names, and `values_to` for their values. section 6.4.6

Turn result-combination columns into a count table

A table with separate `HHH` through `HRR` columns can become a two-column tibble. Each former column name is placed in `result`, and its numeric entry is placed in `count`; filtering positive counts then leaves one row per observed result combination. section 6.4.6

tbl21 %>% 
 pivot_longer(cols = c("HHH", "HRH", "RHH", "RRR", "RHR", "HRR"),
                   names_to = "result",
                   values_to = "count") -> tbl21
head(tbl21)
## # A tibble: 6 × 2
##   result count
##   <chr>  <dbl>
## 1 HHH        0
## 2 HRH        0
## 3 RHH        0
## 4 RRR        0
## 5 RHR        0
## 6 HRR        6

This call pivots six result columns into `result` and `count`, showing how `cols`, `names_to`, and `values_to` define the long-form output. section 6.4.6

For team-by-season analysis, pivoting year-specific win columns changes a wide team record into rows identified by team and year. Selecting `w2017:w2008` and naming the new fields `year` and `wins` produces one record for each unique team-season combination. section 14.2.1

Long format makes several downstream tasks straightforward:

  • Prepare games-played and wins values as labeled groups for paired histograms. section 15.3.2
  • Convert summarized comparison columns into category and total fields for bar charts. section 17.5.1
  • Create grouped long tables before faceted charts by movement or month. section 17.5.1

How Statistics Slam Dunk covers it

How deep it goes
Defines the three core arguments and demonstrates several wide-to-long transformations, without describing implementation internals.
Examples
Uses NBA quarter-result counts, team wins and playoff results, franchise games and wins, and opening-versus-closing totals.
What you can do after
Apply it via tidyr to convert selected columns into named key-value fields for analysis and visualization.
How it connects
Connects tidyr reshaping with dplyr select(), filter(), summarize(), ggplot2, and gghistogram().

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.