Use dplyr’s count() to answer questions such as: how often did each first-quarter outcome occur, or how many games satisfied a scoring condition? It tallies observations by one or more variables and returns the results in a tabular object. section 6.4.1 section 9.3
A practical count() workflow is:
- Prepare the data with operations such as filter() or mutate(), creating the variables or conditions to count. section 6.4.1 section 9.3
- Call count(data, variable) to produce a frequency table with the grouping variable and an automatically generated n column. section 6.4.1 section 6.4.5
- Continue the pipeline with arrange(), mutate(), or related operations to sort counts and calculate percentages or cumulative totals. section 6.4.1 section 6.4.5
- Use count() on a logical expression to check how many rows satisfy a condition, including an integrity check against its opposite. section 9.3
Counting first-quarter outcomes
After creating Q1vF to classify four first-quarter and final-game result combinations, run: count(nbadf3, Q1vF) %>% arrange(desc(n)) -> tbl1 The resulting table reports HH = 783, RR = 550, RH = 365, and HR = 292. Adding mutate() calculates each category’s percentage and cumulative total; the four counts sum to 1,990 observations. section 6.4.1
Checking opposing conditions
To validate a cleaned NBA dataset, count both sides of the game-result condition: NBAboxscores %>% count(teamPTS > opptPTS) The output contains 7,379 TRUE and 7,379 FALSE observations; reversing the comparison produces the same balanced result. section 9.3
count(nbadf3, Q1vF) %>% arrange(desc(n)) -> tbl1 tbl1 %>% mutate(pct_total = n/nrow(nbadf3)*100) %>% mutate(cum_n = cumsum(n)) %>% mutate(cum_pct_total = cumsum(pct_total)) -> tbl1 tbl1$pct_total <- round(tbl1$pct_total, digits = 2) tbl1$cum_pct_total <- round(tbl1$cum_pct_total, digits = 2) print(tbl1) ## Q1vF n pct_total cum_n cum_pct_total ## 1 HH 783 39.35 783 39.35 ## 2 RR 550 27.64 1333 66.98 ## 3 RH 365 18.34 1698 85.33 ## 4 HR 292 14.67 1990 100.00
Browse the complete count(), arrange(), and mutate() pipeline with its printed tibble output. section 6.4.1




