`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
