AE 08: Data wrangling with rowwise/column-wise operations

Suggested answers

Application exercise
Answers
Modified

March 6, 2024

Packages

We will use the following packages in this application exercise.

  • tidyverse: For data import, wrangling, and visualization.
  • janitor: For cleaning column names.
library(tidyverse)
library(janitor)
library(scales)

Powerball

Last class we studied Powerball jackpots over time. Today we will continue this journey and focus on Colorado winners in Match \(N\) Powerball play, prizes available to players who match the red Powerball number and anywhere between 0-4 white ball numbers.

Import and clean the data

The dataset is available for download as a CSV file.

Demo: Import the data file. Store it as powerball_raw.

powerball_raw <- read_csv(file = "data/POWERBALL-from_0001-01-01_to_2024-02-07.csv")
Rows: 2478 Columns: 61
── Column specification ────────────────────────────────────────────────────────
Delimiter: ","
chr (31): Draw date, Last Day To Claim, Winning Numbers, Jackpot, Jackpot Ca...
dbl (30): Powerball, Power Play, Jackpot Winners, Jackpot CO Winners, Match ...

ℹ Use `spec()` to retrieve the full column specification for this data.
ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
powerball_raw
# A tibble: 2,478 × 61
   `Draw date`      `Last Day To Claim` `Winning Numbers` Powerball `Power Play`
   <chr>            <chr>               <chr>                 <dbl>        <dbl>
 1 Monday, 2/5/24   08/03/2024          1 - 2 - 27 - 30 …         9            5
 2 Saturday, 2/3/24 08/01/2024          9 - 11 - 27 - 59…        19            3
 3 Wednesday, 1/31… 07/29/2024          15 - 18 - 19 - 4…        14            2
 4 Monday, 1/29/24  07/27/2024          39 - 41 - 43 - 4…         4            2
 5 Saturday, 1/27/… 07/25/2024          7 - 38 - 65 - 66…        21            2
 6 Wednesday, 1/24… 07/22/2024          1 - 5 - 32 - 50 …         8            4
 7 Monday, 1/22/24  07/20/2024          24 - 25 - 43 - 5…        21            2
 8 Saturday, 1/20/… 07/18/2024          16 - 31 - 34 - 4…        10            3
 9 Wednesday, 1/17… 07/15/2024          18 - 22 - 43 - 6…         2            4
10 Monday, 1/15/24  07/13/2024          13 - 30 - 35 - 4…         4            3
# ℹ 2,468 more rows
# ℹ 56 more variables: Jackpot <chr>, `Jackpot Cash Value` <chr>,
#   `Jackpot Winners` <dbl>, `Jackpot CO Winners` <dbl>, `Match 5 Prize` <chr>,
#   `Match 5 CO Winners` <dbl>, `Match 5 Prize (with Power Play)` <chr>,
#   `Match 5 CO Winners (with Power Play)` <dbl>,
#   `Match 4 + Powerball Prize` <chr>, `Match 4 + Powerball CO Winners` <dbl>,
#   `Match 4 + Powerball Prize (with Power Play)` <chr>, …

Your turn: Clean the raw data to fix the following issues:

  • Standardize the column names using snake_case format.
  • Create columns with appropriate data types for any date variables date of the drawing as well as the weekday. Append these columns to the beginning of the data frame.
  • Fix all of the currency columns to be formatted as numeric types.

Store the cleaned data frame as powerball.

powerball <-  powerball_raw |>
  clean_names() |>
  # separate draw_date into two variables, clean both
  separate_wider_delim(
    cols = draw_date,
    delim = ",",
    names = c(NA, "draw_date")
  ) |>
  mutate(
    draw_date = mdy(draw_date),
    last_day_to_claim = mdy(last_day_to_claim),
    draw_weekday = wday(x = draw_date, label = TRUE),
    .before = last_day_to_claim
  ) |>
  # convert all currency columns to numeric type
  mutate(
    across(
      .cols = c(where(is.character), -contains("winning_numbers")),
      .fn = parse_number
    )
  )
powerball
# A tibble: 2,478 × 62
   draw_date  draw_weekday last_day_to_claim winning_numbers        powerball
   <date>     <ord>        <date>            <chr>                      <dbl>
 1 2024-02-05 Mon          2024-08-03        1 - 2 - 27 - 30 - 67           9
 2 2024-02-03 Sat          2024-08-01        9 - 11 - 27 - 59 - 66         19
 3 2024-01-31 Wed          2024-07-29        15 - 18 - 19 - 41 - 43        14
 4 2024-01-29 Mon          2024-07-27        39 - 41 - 43 - 49 - 64         4
 5 2024-01-27 Sat          2024-07-25        7 - 38 - 65 - 66 - 68         21
 6 2024-01-24 Wed          2024-07-22        1 - 5 - 32 - 50 - 64           8
 7 2024-01-22 Mon          2024-07-20        24 - 25 - 43 - 52 - 63        21
 8 2024-01-20 Sat          2024-07-18        16 - 31 - 34 - 47 - 65        10
 9 2024-01-17 Wed          2024-07-15        18 - 22 - 43 - 61 - 65         2
10 2024-01-15 Mon          2024-07-13        13 - 30 - 35 - 49 - 59         4
# ℹ 2,468 more rows
# ℹ 57 more variables: power_play <dbl>, jackpot <dbl>,
#   jackpot_cash_value <dbl>, jackpot_winners <dbl>, jackpot_co_winners <dbl>,
#   match_5_prize <dbl>, match_5_co_winners <dbl>,
#   match_5_prize_with_power_play <dbl>,
#   match_5_co_winners_with_power_play <dbl>, match_4_powerball_prize <dbl>,
#   match_4_powerball_co_winners <dbl>, …

Analyze the data

Our goal is to reproduce the following visualization:

In order to accomplish this, we have a few challenges ahead. We will need to:

  • Determine the year for every drawing
  • Calculate the mean and standard error of the number of winners for each Match \(N\) + Powerball prize for every year
  • Structure the data frame so we have one row for each year and prize, and separate columns for the means and standard errors

Generate the year variable

Your turn: Generate a year variable from the draw_date column.

powerball |>
  # generate year variable
  mutate(
    year = year(x = draw_date),
    .before = everything()
  )
# A tibble: 2,478 × 63
    year draw_date  draw_weekday last_day_to_claim winning_numbers     powerball
   <dbl> <date>     <ord>        <date>            <chr>                   <dbl>
 1  2024 2024-02-05 Mon          2024-08-03        1 - 2 - 27 - 30 - …         9
 2  2024 2024-02-03 Sat          2024-08-01        9 - 11 - 27 - 59 -…        19
 3  2024 2024-01-31 Wed          2024-07-29        15 - 18 - 19 - 41 …        14
 4  2024 2024-01-29 Mon          2024-07-27        39 - 41 - 43 - 49 …         4
 5  2024 2024-01-27 Sat          2024-07-25        7 - 38 - 65 - 66 -…        21
 6  2024 2024-01-24 Wed          2024-07-22        1 - 5 - 32 - 50 - …         8
 7  2024 2024-01-22 Mon          2024-07-20        24 - 25 - 43 - 52 …        21
 8  2024 2024-01-20 Sat          2024-07-18        16 - 31 - 34 - 47 …        10
 9  2024 2024-01-17 Wed          2024-07-15        18 - 22 - 43 - 61 …         2
10  2024 2024-01-15 Mon          2024-07-13        13 - 30 - 35 - 49 …         4
# ℹ 2,468 more rows
# ℹ 57 more variables: power_play <dbl>, jackpot <dbl>,
#   jackpot_cash_value <dbl>, jackpot_winners <dbl>, jackpot_co_winners <dbl>,
#   match_5_prize <dbl>, match_5_co_winners <dbl>,
#   match_5_prize_with_power_play <dbl>,
#   match_5_co_winners_with_power_play <dbl>, match_4_powerball_prize <dbl>,
#   match_4_powerball_co_winners <dbl>, …

Calculate means and standard errors

Your turn: Calculate the mean and standard error for each of the Match \(N\) + Powerball prizes for each year.

Tip

Recall the formula for the standard error of a sample mean is:

\[ \begin{aligned} \text{s.e.} &= \sqrt{\frac{\text{Variance}(X)}{\text{Sample size}}} \\ &= \frac{\text{Standard deviation}(X)}{\sqrt{\text{Sample size}}} \end{aligned} \]

powerball |>
  # generate year variable
  mutate(
    year = year(x = draw_date),
    .before = everything()
  ) |>
  # calculate mean and se for the match N powerball winner columns
  summarize(
    across(
      .cols = starts_with("match") & contains("powerball") & ends_with("winners"),
      .fns = list(mean = mean, se = \(x) sd(x) / sqrt(n()))
    ),
    # do this for each year in the dataset
    .by = year
  )
# A tibble: 24 × 11
    year match_4_powerball_co_wi…¹ match_4_powerball_co…² match_3_powerball_co…³
   <dbl>                     <dbl>                  <dbl>                  <dbl>
 1  2024                    0                      0                        6.88
 2  2023                    0.218                  0.0475                  11.6 
 3  2022                    0.153                  0.0363                  10.1 
 4  2021                    0.138                  0.0312                   9.88
 5  2020                    0.0762                 0.0260                   7.49
 6  2019                    0.125                  0.0326                  10.8 
 7  2018                    0.221                  0.0510                  11.3 
 8  2017                    0.192                  0.0412                  13.4 
 9  2016                    0.295                  0.103                   19.2 
10  2015                    0.288                  0.0839                  12.9 
# ℹ 14 more rows
# ℹ abbreviated names: ¹​match_4_powerball_co_winners_mean,
#   ²​match_4_powerball_co_winners_se, ³​match_3_powerball_co_winners_mean
# ℹ 7 more variables: match_3_powerball_co_winners_se <dbl>,
#   match_2_powerball_co_winners_mean <dbl>,
#   match_2_powerball_co_winners_se <dbl>,
#   match_1_powerball_co_winners_mean <dbl>, …

Clean up column names

Your turn: Remove "powerball_co_winners_" from each column name.

Tip

rename() does not allow use of the across() function. Instead, check out rename_with() from the dplyr package.

Tip

stringr contains many functions for working with character strings. Check out the cheat sheet for examples!

powerball |>
  # generate year variable
  mutate(
    year = year(x = draw_date),
    .before = everything()
  ) |>
  # calculate mean and se for the match N powerball winner columns
  summarize(
    across(
      .cols = starts_with("match") & contains("powerball") & ends_with("winners"),
      .fns = list(mean = mean, se = \(x) sd(x) / sqrt(n()))
    ),
    # do this for each year in the dataset
    .by = year
  ) |>
  # remove extraneous string from columns
  rename_with(
    .cols = starts_with("match"),
    .fn = \(x) str_remove(string = x, pattern = "powerball_co_winners_")
  )
# A tibble: 24 × 11
    year match_4_mean match_4_se match_3_mean match_3_se match_2_mean match_2_se
   <dbl>        <dbl>      <dbl>        <dbl>      <dbl>        <dbl>      <dbl>
 1  2024       0          0              6.88      1.90          128.      30.5 
 2  2023       0.218      0.0475        11.6       1.15          236.      21.4 
 3  2022       0.153      0.0363        10.1       1.66          205.      34.4 
 4  2021       0.138      0.0312         9.88      0.804         198.      15.5 
 5  2020       0.0762     0.0260         7.49      0.481         156.       7.62
 6  2019       0.125      0.0326        10.8       1.18          212.      20.9 
 7  2018       0.221      0.0510        11.3       1.04          236.      21.4 
 8  2017       0.192      0.0412        13.4       1.89          270.      34.8 
 9  2016       0.295      0.103         19.2       5.47          386.     103.  
10  2015       0.288      0.0839        12.9       1.55          233.      26.1 
# ℹ 14 more rows
# ℹ 4 more variables: match_1_mean <dbl>, match_1_se <dbl>, match_0_mean <dbl>,
#   match_0_se <dbl>

Restructure data frame to appropriate form for visualization

Demo: We need the structure to be one row for each year and prize (i.e. 0, 1, 2, 3, 4) and separate columns for the means and standard errors. We can use pivot_longer() to accomplish this task, but it’s a bit more complicated than past pivoting operations since the column names contain both a variable (e.g. match_4) and a variable name (i.e. mean or se). We can leverage the names_to argument and its ability to pass in a character vector with multiple values to create multiple columns in the resulting data frame. According to the documentation,

If length > 1, multiple columns will be created. In this case, one of names_sep or names_pattern must be supplied to specify how the column names should be split. There are also two additional character values you can take advantage of:

  • NA will discard the corresponding component of the column name.

  • ".value" indicates that the corresponding component of the column name defines the name of the output column containing the cell values, overriding values_to entirely.

powerball |>
  # generate year variable
  mutate(
    year = year(x = draw_date),
    .before = everything()
  ) |>
  # calculate mean and se for the match N powerball winner columns
  summarize(
    across(
      .cols = starts_with("match") & contains("powerball") & ends_with("winners"),
      .fns = list(mean = mean, se = \(x) sd(x) / sqrt(n())),
      .names = "{.col}_{.fn}"
    ),
    # do this for each year in the dataset
    .by = year
  ) |>
  # remove extraneous string from columns
  rename_with(
    .cols = starts_with("match"),
    .fn = \(x) str_remove(string = x, pattern = "powerball_co_winners_")
  ) |>
  # restructure to one row per year per game
  # separate columns for mean and se
  pivot_longer(
    cols = -year,
    # columns contain a variable and a variable name
    names_to = c("game", ".value"),
    # ignore column prefix
    names_prefix = "match_",
    # separating character
    names_sep = "_"
  ) |>
  # reformat game column values for visualization
  mutate(game = str_glue("Match {game}"))
# A tibble: 120 × 4
    year game        mean       se
   <dbl> <glue>     <dbl>    <dbl>
 1  2024 Match 4    0       0     
 2  2024 Match 3    6.88    1.90  
 3  2024 Match 2  128.     30.5   
 4  2024 Match 1 1009.    237.    
 5  2024 Match 0 2440     555.    
 6  2023 Match 4    0.218   0.0475
 7  2023 Match 3   11.6     1.15  
 8  2023 Match 2  236.     21.4   
 9  2023 Match 1 1797.    160.    
10  2023 Match 0 4300.    384.    
# ℹ 110 more rows

Plot the data

Demo: Now that we have the appropriate data structure, we can create the visualization.

powerball |>
  # generate year variable
  mutate(
    year = year(x = draw_date),
    .before = everything()
  ) |>
  # calculate mean and se for the match N powerball winner columns
  summarize(
    across(
      .cols = starts_with("match") & contains("powerball") & ends_with("winners"),
      .fns = list(mean = mean, se = \(x) sd(x) / sqrt(n())),
      .names = "{.col}_{.fn}"
    ),
    # do this for each year in the dataset
    .by = year
  ) |>
  # remove extraneous string from columns
  rename_with(
    .cols = starts_with("match"),
    .fn = \(x) str_remove(string = x, pattern = "powerball_co_winners_")
  ) |>
  # restructure to one row per year per game
  # separate columns for mean and se
  pivot_longer(
    cols = -year,
    # columns contain a variable and a variable name
    names_to = c("game", ".value"),
    # ignore column prefix
    names_prefix = "match_",
    # separating character
    names_sep = "_"
  ) |>
  # reformat game column values for visualization
  mutate(game = str_glue("Match {game}")) |>
  ggplot(mapping = aes(x = year, y = mean)) +
  geom_point() +
  geom_linerange(mapping = aes(
    ymin = mean - se,
    ymax = mean + se
  )) +
  facet_wrap(facets = vars(game), scales = "free_y") +
  labs(
    title = "The number of Match N Powerball Prize winners trends downward",
    subtitle = "Average number of prize winners (plus/minus 1 standard error)",
    x = "Year",
    y = "Number of Colorado winners",
    caption = "Source: Colorado Lottery"
  ) +
  theme_minimal()

sessioninfo::session_info()
─ Session info ───────────────────────────────────────────────────────────────
 setting  value
 version  R version 4.3.2 (2023-10-31)
 os       macOS Ventura 13.5.2
 system   aarch64, darwin20
 ui       X11
 language (EN)
 collate  en_US.UTF-8
 ctype    en_US.UTF-8
 tz       America/New_York
 date     2024-02-24
 pandoc   3.1.1 @ /Applications/RStudio.app/Contents/Resources/app/quarto/bin/tools/ (via rmarkdown)

─ Packages ───────────────────────────────────────────────────────────────────
 package     * version date (UTC) lib source
 bit           4.0.5   2022-11-15 [1] CRAN (R 4.3.0)
 bit64         4.0.5   2020-08-30 [1] CRAN (R 4.3.0)
 cli           3.6.2   2023-12-11 [1] CRAN (R 4.3.1)
 colorspace    2.1-0   2023-01-23 [1] CRAN (R 4.3.0)
 crayon        1.5.2   2022-09-29 [1] CRAN (R 4.3.0)
 digest        0.6.34  2024-01-11 [1] CRAN (R 4.3.1)
 dplyr       * 1.1.4   2023-11-17 [1] CRAN (R 4.3.1)
 evaluate      0.23    2023-11-01 [1] CRAN (R 4.3.1)
 fansi         1.0.6   2023-12-08 [1] CRAN (R 4.3.1)
 farver        2.1.1   2022-07-06 [1] CRAN (R 4.3.0)
 fastmap       1.1.1   2023-02-24 [1] CRAN (R 4.3.0)
 forcats     * 1.0.0   2023-01-29 [1] CRAN (R 4.3.0)
 generics      0.1.3   2022-07-05 [1] CRAN (R 4.3.0)
 ggplot2     * 3.4.4   2023-10-12 [1] CRAN (R 4.3.1)
 glue          1.7.0   2024-01-09 [1] CRAN (R 4.3.1)
 gtable        0.3.4   2023-08-21 [1] CRAN (R 4.3.0)
 here          1.0.1   2020-12-13 [1] CRAN (R 4.3.0)
 hms           1.1.3   2023-03-21 [1] CRAN (R 4.3.0)
 htmltools     0.5.7   2023-11-03 [1] CRAN (R 4.3.1)
 htmlwidgets   1.6.4   2023-12-06 [1] CRAN (R 4.3.1)
 janitor     * 2.2.0   2023-02-02 [1] CRAN (R 4.3.0)
 jsonlite      1.8.8   2023-12-04 [1] CRAN (R 4.3.1)
 knitr         1.45    2023-10-30 [1] CRAN (R 4.3.1)
 labeling      0.4.3   2023-08-29 [1] CRAN (R 4.3.0)
 lifecycle     1.0.4   2023-11-07 [1] CRAN (R 4.3.1)
 lubridate   * 1.9.3   2023-09-27 [1] CRAN (R 4.3.1)
 magrittr      2.0.3   2022-03-30 [1] CRAN (R 4.3.0)
 munsell       0.5.0   2018-06-12 [1] CRAN (R 4.3.0)
 pillar        1.9.0   2023-03-22 [1] CRAN (R 4.3.0)
 pkgconfig     2.0.3   2019-09-22 [1] CRAN (R 4.3.0)
 purrr       * 1.0.2   2023-08-10 [1] CRAN (R 4.3.0)
 R6            2.5.1   2021-08-19 [1] CRAN (R 4.3.0)
 ragg          1.2.7   2023-12-11 [1] CRAN (R 4.3.1)
 readr       * 2.1.5   2024-01-10 [1] CRAN (R 4.3.1)
 rlang         1.1.3   2024-01-10 [1] CRAN (R 4.3.1)
 rmarkdown     2.25    2023-09-18 [1] CRAN (R 4.3.1)
 rprojroot     2.0.4   2023-11-05 [1] CRAN (R 4.3.1)
 rstudioapi    0.15.0  2023-07-07 [1] CRAN (R 4.3.0)
 scales      * 1.2.1   2024-01-18 [1] Github (r-lib/scales@c8eb772)
 sessioninfo   1.2.2   2021-12-06 [1] CRAN (R 4.3.0)
 snakecase     0.11.1  2023-08-27 [1] CRAN (R 4.3.0)
 stringi       1.8.3   2023-12-11 [1] CRAN (R 4.3.1)
 stringr     * 1.5.1   2023-11-14 [1] CRAN (R 4.3.1)
 systemfonts   1.0.5   2023-10-09 [1] CRAN (R 4.3.1)
 textshaping   0.3.7   2023-10-09 [1] CRAN (R 4.3.1)
 tibble      * 3.2.1   2023-03-20 [1] CRAN (R 4.3.0)
 tidyr       * 1.3.0   2023-01-24 [1] CRAN (R 4.3.0)
 tidyselect    1.2.0   2022-10-10 [1] CRAN (R 4.3.0)
 tidyverse   * 2.0.0   2023-02-22 [1] CRAN (R 4.3.0)
 timechange    0.2.0   2023-01-11 [1] CRAN (R 4.3.0)
 tzdb          0.4.0   2023-05-12 [1] CRAN (R 4.3.0)
 utf8          1.2.4   2023-10-22 [1] CRAN (R 4.3.1)
 vctrs         0.6.5   2023-12-01 [1] CRAN (R 4.3.1)
 vroom         1.6.5   2023-12-05 [1] CRAN (R 4.3.1)
 withr         2.5.2   2023-10-30 [1] CRAN (R 4.3.1)
 xfun          0.41    2023-11-01 [1] CRAN (R 4.3.1)
 yaml          2.3.8   2023-12-11 [1] CRAN (R 4.3.1)

 [1] /Library/Frameworks/R.framework/Versions/4.3-arm64/Resources/library

──────────────────────────────────────────────────────────────────────────────