Last updated: 2021-09-24

Checks: 7 0

Knit directory: myTidyTuesday/

This reproducible R Markdown analysis was created with workflowr (version 1.6.2). The Checks tab describes the reproducibility checks that were applied when the results were created. The Past versions tab lists the development history.


Great! Since the R Markdown file has been committed to the Git repository, you know the exact version of the code that produced these results.

Great job! The global environment was empty. Objects defined in the global environment can affect the analysis in your R Markdown file in unknown ways. For reproduciblity it’s best to always run the code in an empty environment.

The command set.seed(20210907) was run prior to running the code in the R Markdown file. Setting a seed ensures that any results that rely on randomness, e.g. subsampling or permutations, are reproducible.

Great job! Recording the operating system, R version, and package versions is critical for reproducibility.

Nice! There were no cached chunks for this analysis, so you can be confident that you successfully produced the results during this run.

Great job! Using relative paths to the files within your workflowr project makes it easier to run your code on other machines.

Great! You are using Git for version control. Tracking code development and connecting the code version to the results is critical for reproducibility.

The results in this page were generated with repository version 699e663. See the Past versions tab to see a history of the changes made to the R Markdown and HTML files.

Note that you need to be careful to ensure that all relevant files for the analysis have been committed to Git prior to generating the results (you can use wflow_publish or wflow_git_commit). workflowr only checks the R Markdown file, but you know if there are other scripts or data files that it depends on. Below is the status of the Git repository when the results were generated:


Ignored files:
    Ignored:    .Rhistory
    Ignored:    .Rproj.user/
    Ignored:    catboost_info/
    Ignored:    data/2021-09-08/
    Ignored:    data/CNHI_Excel_Chart.xlsx
    Ignored:    data/CommunityTreemap.jpeg
    Ignored:    data/Community_Roles.jpeg
    Ignored:    data/YammerDigitalDataScienceMembership.xlsx
    Ignored:    data/acs_poverty.rds
    Ignored:    data/fmhpi.rds
    Ignored:    data/grainstocks.rds
    Ignored:    data/hike_data.rds
    Ignored:    data/us_states.rds
    Ignored:    data/us_states_hexgrid.geojson
    Ignored:    data/weatherstats_toronto_daily.csv

Untracked files:
    Untracked:  code/YammerReach.R
    Untracked:  code/work list batch targets.R
    Untracked:  figure/

Note that any generated files, e.g. HTML, png, CSS, etc., are not included in this status report because it is ok for generated content to have uncommitted changes.


These are the previous versions of the repository in which changes were made to the R Markdown (analysis/BeerProduction.Rmd) and HTML (docs/BeerProduction.html) files. If you’ve configured a remote Git repository (see ?wflow_git_remote), click on the hyperlinks in the table below to view the files as they were in that past version.

File Version Author Date Message
Rmd 699e663 opus1993 2021-09-24 adopt viridis H palette and trim out the tables

Import this week’s data

brewing_materials <- readr::read_csv("https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-03-31/brewing_materials.csv") %>%
  mutate(date = ymd(paste0(year, "/", month, "/1")))
beer_taxed <- readr::read_csv("https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-03-31/beer_taxed.csv")
brewer_size <- readr::read_csv("https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-03-31/brewer_size.csv")
beer_states <- readr::read_csv("https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-03-31/beer_states.csv")

Exploration

skimr::skim(beer_states)
# 19 year/states with missing barrels

skimr::skim(brewing_materials)
table(brewing_materials$type)
# opportunity to examine the proportional trends of Corn vresus Sugar/syrups use

skimr::skim(beer_taxed)

skimr::skim(brewer_size)
table(brewer_size$brewer_size)

Total all barrels produced by state per year (regardless of type)

all_barrels <-
  beer_states %>%
  na.omit() %>%
  filter(state != "total") %>%
  group_by(state, year) %>%
  summarise(
    barrels = sum(barrels),
    .groups = "drop"
  )

The top 5 states with largest increase in barrels from 2008 to 2019

increase_states <-
  all_barrels %>%
  group_by(state) %>%
  mutate(total_barrels = cumsum(barrels)) %>%
  filter(year %in% c(2008, 2019)) %>%
  mutate(pct_chg = (total_barrels - lag(total_barrels)) / lag(total_barrels)) %>%
  ungroup() %>%
  top_n(5, pct_chg) %>%
  pull(state)

increase_states %>%
  knitr::kable()
x
AL
CT
ND
RI
TN
# Lets get the state names
states <- tibble(state = state.abb, state_name = state.name)

beer_df <-
  beer_states %>%
  na.omit() %>%
  filter(state != "total") %>%
  group_by(state, year) %>%
  summarise(
    barrels = sum(barrels),
    .groups = "drop"
  ) %>%
  mutate(total_barrels = cumsum(barrels)) %>%
  left_join(states, by = "state")

Lets have a look at the materials trends. What ingredients are used in beer production?

brewing_materials %>%
  filter(
    !str_detect(material_type, "Total"),
    !(month == 12 & year %in% 2014:2015)
  ) %>% # remove the subtotals) %>%
  filter(date == max(date)) %>%
  mutate(type = fct_reorder(type, month_current)) %>%
  ggplot(aes(type, month_current / 1000000, fill = type)) +
  geom_col() +
  scale_y_continuous(breaks = scales::pretty_breaks()) +
  coord_flip() +
  theme(
    legend.position = "",
    panel.grid.major.y = element_blank()
  ) +
  labs(
    x = "",
    y = "Million Pounds",
    title = "Ingredients in US Beer Production, in the month of December 2019",
    subtitle = "US Alcohol and Tobacco Tax and Trade Bureau",
    caption = "@Jim_Gruman | #TidyTuesday"
  )

brewing_materials %>%
  filter(
    !str_detect(type, "Total"), year < 2016,
    !(month == 12 & year %in% 2014:2015)
  ) %>% # remove the subtotals
  mutate(type = fct_reorder2(type,
    date,
    month_current,
    .fun = last2
  )) %>%
  ggplot(aes(date,
    month_current / 1000000,
    color = type
  )) +
  geom_line() +
  labs(
    x = "",
    y = "Million Pounds",
    color = "Material",
    title = "Ingredients in US Beer Production, 2008-2016",
    subtitle = "US Alcohol and Tobacco Tax and Trade Bureau",
    caption = "@Jim_Gruman | #TidyTuesday"
  ) +
  scale_radius(range = c(1, 6)) +
  scale_x_date(
    date_breaks = "2 years",
    date_labels = "%Y"
  )

Tidymetrics

cross_by_dimensions <- function(tbl, ..., add = TRUE, max_dimensions = NULL, collect_fun = NULL) {
  g_vars <- dplyr::group_vars(tbl)
  columns <- ensyms(...)
  tbl <- tbl %>%
    ungroup() %>%
    mutate_at(
      vars(!!!columns),
      as.character
    )
  if (!is.null(max_dimensions)) {
    tbl <- tbl %>% cross_by_dimensions_limited(
      columns,
      max_dimensions = max_dimensions,
      collect_fun = collect_fun
    )
  } else {
    for (column in columns) {
      tbl <- tbl %>%
        mutate(`:=`(!!column, "All")) %>%
        union_all(tbl)
      if (!is.null(collect_fun)) {
        tbl <- collect_fun(tbl)
      }
    }
  }
  tbl %>%
    group_by_at(vars(all_of(g_vars))) %>%
    group_by(!!!columns,
      .add = add
    )
}


brewing_summarized <- brewing_materials %>%
  rename(material = type) %>%
  filter(
    !str_detect(material_type, "Total"),
    year < 2016,
    !(month == 12 & year %in% 2014:2015)
  ) %>%
  cross_by_dimensions(material_type, material) %>% # duplicates the data to summarize it
  cross_by_periods(c("month", "quarter", "year")) %>%
  summarize(
    total_pounds = sum(month_current),
    .groups = "drop"
  )

brewing_summarized %>%
  filter(
    material_type != "All",
    material != "All",
    period == "month"
  ) %>%
  mutate(material = fct_reorder2(material,
    date,
    total_pounds,
    .fun = last2
  )) %>%
  ggplot(aes(date,
    total_pounds / 1000000,
    color = material
  )) +
  geom_line() +
  scale_x_date(
    date_breaks = "2 years",
    date_labels = "%Y"
  ) +
  labs(
    x = "Date",
    y = "Million Pounds",
    color = "Material",
    title = "Ingredients in US Beer Production, 2008-2016:  Monthly",
    subtitle = "US Alcohol and Tobacco Tax and Trade Bureau",
    caption = "@Jim_Gruman | #TidyTuesday"
  )

brewing_summarized %>%
  filter(
    material_type != "All",
    material != "All",
    period == "quarter"
  ) %>%
  mutate(material = fct_reorder2(material,
    date,
    total_pounds,
    .fun = last2
  )) %>%
  ggplot(aes(date,
    total_pounds / 1000000,
    color = material
  )) +
  geom_line() +
  labs(
    x = "Date",
    y = "Million Pounds",
    color = "Material",
    title = "Ingredients in US Beer Production, 2008-2016: Quarterly",
    subtitle = "US Alcohol and Tobacco Tax and Trade Bureau",
    caption = "@Jim_Gruman | #TidyTuesday"
  )

brewing_summarized %>%
  filter(
    material_type != "All",
    material != "All",
    period == "year"
  ) %>%
  mutate(material = fct_reorder2(material,
    date,
    total_pounds,
    .fun = last2
  )) %>%
  ggplot(aes(date,
    total_pounds / 1000000,
    color = material
  )) +
  geom_line() +
  labs(
    x = "Date",
    y = "Million Pounds",
    color = "Material",
    title = "Ingredients in US Beer Production, 2008-2016: Annually",
    subtitle = "US Alcohol and Tobacco Tax and Trade Bureau",
    caption = "@Jim_Gruman | #TidyTuesday"
  )

brewing_materials %>%
  filter(material_type == "Total Used", year < 2016) %>%
  mutate(month = factor(month, labels = month.abb)) %>%
  ggplot(aes(
    x = month,
    y = month_current / 1000000,
    group = factor(year),
    color = factor(year)
  )) +
  geom_line() +
  expand_limits(y = 0) +
  labs(
    x = "",
    y = "Million Pounds",
    color = "Year",
    title = "Ingredients in US Beer Production, 2008-2016: Each Month",
    subtitle = "US Alcohol and Tobacco Tax and Trade Bureau",
    caption = "@Jim_Gruman | #TidyTuesday"
  ) +
  scale_y_continuous(labels = scales::comma_format())

remotes::install_github("ramnathv/shinymetrics")
remotes::install_github("ramnathv/shinybones")

brewing_metrics <- create_metrics(brewing_summarized)

library(shinymetrics)

# interactive plotly visualization of grouped time multi-dimensional BI
preview_metric(brewing_metrics$production_NA_total_pounds)
# change the dropdown from "last year" to "all time" because 2019 is not in this dataset
brewer_size %>%
  filter(
    brewer_size != "Total",
    !is.na(total_barrels)
  ) %>%
  mutate(
    brewer_size = fct_lump_n(brewer_size,
      n = 5,
      w = total_barrels,
      other_level = "1 to 100,000 Barrels"
    ),
    barrel_number = coalesce(parse_number(as.character(brewer_size)), 1),
    brewer_size = fct_reorder(brewer_size, barrel_number)
  ) %>%
  ggplot(aes(as_factor(year),
    total_barrels / 1000000,
    fill = brewer_size
  )) +
  geom_col() +
  scale_y_continuous(labels = scales::comma_format()) +
  labs(
    x = "Year",
    y = "Million Barrels",
    fill = "Brewer Size",
    title = "Total Production, by US Brewer Size in 2019",
    subtitle = "US Alcohol and Tobacco Tax and Trade Bureau",
    caption = "@Jim_Gruman | #TidyTuesday"
  )

Where is Beer produced?

beer_df %>%
  ggplot(aes(year, barrels,
    group = state
  )) +
  geom_line(aes(color = state), show.legend = FALSE) +
  gghighlight(
    state %in% increase_states,
    label_key = state_name,
    label_params = list(
      size = 3,
      color = "black",
      family = "Arial Narrow",
      fill = "grey95",
      width = 2,
      alpha = 1,
      label.r = 0.1,
      segment.alpha = 0
    ),
    unhighlighted_params = list(color = "grey88")
  ) +
  labs(
    x = "Year",
    y = "Total number of barrels produced",
    title = "States with the Largest Increase in Beer Production, 2008-2019",
    subtitle = "US Alcohol and Tobacco Tax and Trade Bureau",
    caption = "@Jim_Gruman | #TidyTuesday"
  ) +
  scale_x_continuous(breaks = scales::pretty_breaks()) +
  scale_y_log10(labels = scales::label_number()) +
  theme(
    panel.grid = element_blank(),
    panel.grid.major = element_blank()
  )

states_percents_2019 <- beer_states %>%
  filter(year == max(year), state != "total") %>%
  group_by(state) %>%
  mutate(percent = barrels / sum(barrels)) %>%
  ungroup()

states <- st_as_sf(maps::map("state", plot = FALSE, fill = TRUE))

states_percents_2019 %>%
  mutate(ID = if_else(state != "DC",
    str_to_lower(state.name[match(state, state.abb)]),
    "district of columbia"
  )) %>%
  inner_join(states, by = "ID") %>%
  ggplot() +
  geom_sf(aes(geometry = geom, fill = percent)) +
  facet_wrap(~type, nrow = 2) +
  scale_fill_continuous(labels = scales::percent) +
  labs(
    title = "In Each State, What is the Highest Proportion of Beer Consumed?",
    subtitle = "US Alcohol and Tobacco Tax and Trade Bureau",
    caption = "@Jim_Gruman | #TidyTuesday",
    fill = "% Percent"
  ) +
  theme_jim() +
  theme(
    legend.position = c(0.7, 0.2),
    panel.grid.major = element_blank(),
    axis.text.x = element_blank(),
    axis.text.y = element_blank()
  )

An animated map. Because it’s TidyTuesday

p <- beer_states %>%
  filter(state != "total") %>%
  group_by(state, year) %>%
  mutate(percent = barrels / sum(barrels)) %>%
  ungroup() %>%
  mutate(ID = if_else(state != "DC",
    str_to_lower(state.name[match(state, state.abb)]),
    "district of columbia"
  )) %>%
  inner_join(states, by = "ID") %>%
  ggplot(aes(
    geometry = geom,
    fill = percent
  )) +
  geom_sf() +
  transition_time(year) +
  facet_wrap(~type, nrow = 2) +
  labs(
    title = "In Each State, What is the Highest Proportion of Beer Consumed? {as.integer(frame_time)}",
    subtitle = "US Alcohol and Tobacco Tax and Trade Bureau, 2008-2019",
    caption = "@Jim_Gruman | #TidyTuesday",
    fill = "% Percent"
  ) +
  theme_jim() +
  theme(
    legend.position = c(0.7, 0.2),
    panel.grid.major = element_blank(),
    axis.text.x = element_blank(),
    axis.text.y = element_blank()
  )

animate(p, width = 900, height = 750, end_pause = 50, renderer = gifski_renderer())

What are the relationships between the materials used? (using resampling methods)

For example, how much sugar do beer producers need per pound of malt?

brewing_materials %>%
  count(type, wt = month_current, sort = TRUE) %>%
  knitr::kable()
type n
Total Used 53559516695
Total Grain products 44734903124
Malt and malt products 32697313882
Total Non-Grain products 8824613571
Sugar and syrups 6653104081
Rice and rice products 5685742541
Corn and corn products 5207759409
Hops (dry) 1138840132
Other 998968470
Barley and barley products 941444745
Wheat and wheat products 202642547
Hops (used as extracts) 33700888
brewing_filtered <- brewing_materials %>%
  filter(
    !str_detect(type, "Total"), year < 2016,
    !(month == 12 & year %in% 2014:2015)
  )

Explore the relationship between ingredients

brewing_df <- brewing_filtered %>%
  select(date, type, month_current) %>%
  pivot_wider(
    names_from = type,
    values_from = month_current
  ) %>%
  janitor::clean_names()

# is there a remote correlation between
brewing_df %>%
  ggplot(aes(malt_and_malt_products, sugar_and_syrups)) +
  geom_smooth(method = "lm") +
  geom_point() +
  labs(title = "What is the relationship between malt and sugar ingredients?")

A simple linear model

# force the y-intercept to be zero (no beer, no malt, no sugar)
beer_fit <- lm(sugar_and_syrups ~ 0 + malt_and_malt_products, data = brewing_df)

summary(beer_fit)

Call:
lm(formula = sugar_and_syrups ~ 0 + malt_and_malt_products, data = brewing_df)

Residuals:
      Min        1Q    Median        3Q       Max 
-29985291  -6468052    174001   7364462  23462837 

Coefficients:
                       Estimate Std. Error t value Pr(>|t|)    
malt_and_malt_products 0.205804   0.003446   59.72   <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 11480000 on 93 degrees of freedom
Multiple R-squared:  0.9746,    Adjusted R-squared:  0.9743 
F-statistic:  3567 on 1 and 93 DF,  p-value: < 2.2e-16
broom::tidy(beer_fit) %>%
  knitr::kable()
term estimate std.error statistic p.value
malt_and_malt_products 0.205804 0.0034461 59.72037 0

Bootstrap Resampling

to arrive at a confidence interval for a linear model

beer_boot <- bootstraps(data = brewing_df, times = 1e3, apparent = FALSE)
beer_models <- beer_boot %>%
  dplyr::mutate(
    model = purrr::map(splits, ~ lm(sugar_and_syrups ~ 0 + malt_and_malt_products,
      data = .
    )),
    coef_info = purrr::map(model, tidy)
  )

beer_coefs <- beer_models %>%
  unnest(coef_info)

Evaluate results

What is the distribution of the estimates for the model?

beer_coefs %>%
  ggplot(aes(estimate)) +
  geom_histogram(alpha = 0.7) +
  labs(title = "Malt Coefficient Estimate for predicting Sugar and Syrups")

Our bootstrap confidence intervals:

int_pctl(beer_models, coef_info)
# A tibble: 1 x 6
  term                   .lower .estimate .upper .alpha .method   
  <chr>                   <dbl>     <dbl>  <dbl>  <dbl> <chr>     
1 malt_and_malt_products  0.199     0.206  0.213   0.05 percentile
beer_aug <- beer_models %>%
  dplyr::mutate(augmented = purrr::map(model, augment)) %>%
  unnest(augmented)

beer_aug %>%
  ggplot(aes(malt_and_malt_products, sugar_and_syrups)) +
  geom_line(aes(y = .fitted, group = id), alpha = 0.1, color = "cyan3") +
  geom_point() +
  labs(title = "Bootstrap Resampling Model Estimates Confidence Interval")

And finally, my tidytuesday tweet:

tweetrmd::include_tweet("https://twitter.com/jim_gruman/status/1246645041663221765")

sessionInfo()
R version 4.1.1 (2021-08-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19043)

Matrix products: default

locale:
[1] LC_COLLATE=English_United States.1252 
[2] LC_CTYPE=English_United States.1252   
[3] LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C                          
[5] LC_TIME=English_United States.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
 [1] transformr_0.1.3   gganimate_1.0.7    sf_1.0-2           maps_3.3.0        
 [5] yardstick_0.0.8    workflowsets_0.1.0 workflows_0.2.3    tune_0.1.6        
 [9] rsample_0.1.0      recipes_0.1.16     parsnip_0.1.7.900  modeldata_0.1.1   
[13] infer_1.0.0        dials_0.0.10       scales_1.1.1       broom_0.7.9       
[17] tidymodels_0.1.3   gghighlight_0.3.2  GGally_2.1.2       tidymetrics_0.0.1 
[21] lubridate_1.7.10   forcats_0.5.1      stringr_1.4.0      dplyr_1.0.7       
[25] purrr_0.3.4        readr_2.0.1        tidyr_1.1.3        tibble_3.1.4      
[29] ggplot2_3.3.5      tidyverse_1.3.1    workflowr_1.6.2   

loaded via a namespace (and not attached):
  [1] readxl_1.3.1       backports_1.2.1    systemfonts_1.0.2 
  [4] plyr_1.8.6         splines_4.1.1      listenv_0.8.0     
  [7] digest_0.6.27      foreach_1.5.1      htmltools_0.5.2   
 [10] viridis_0.6.1      fansi_0.5.0        magrittr_2.0.1    
 [13] tzdb_0.1.2         globals_0.14.0     extrafont_0.17    
 [16] modelr_0.1.8       gower_0.2.2        vroom_1.5.5       
 [19] R.utils_2.10.1     extrafontdb_1.0    hardhat_0.1.6     
 [22] lpSolve_5.6.15     prettyunits_1.1.1  colorspace_2.0-2  
 [25] ggrepel_0.9.1      rvest_1.0.1        textshaping_0.3.5 
 [28] haven_2.4.3        xfun_0.26          crayon_1.4.1      
 [31] jsonlite_1.7.2     survival_3.2-11    iterators_1.0.13  
 [34] glue_1.4.2         gtable_0.3.0       ipred_0.9-12      
 [37] R.cache_0.15.0     tweetrmd_0.0.9     Rttf2pt1_1.3.9    
 [40] future.apply_1.8.1 DBI_1.1.1          Rcpp_1.0.7        
 [43] viridisLite_0.4.0  progress_1.2.2     units_0.7-2       
 [46] bit_4.0.4          GPfit_1.0-8        proxy_0.4-26      
 [49] lava_1.6.10        prodlim_2019.11.13 httr_1.4.2        
 [52] RColorBrewer_1.1-2 ellipsis_0.3.2     R.methodsS3_1.8.1 
 [55] pkgconfig_2.0.3    reshape_0.8.8      farver_2.1.0      
 [58] nnet_7.3-16        sass_0.4.0         dbplyr_2.1.1      
 [61] janitor_2.1.0      utf8_1.2.2         here_1.0.1        
 [64] labeling_0.4.2     tidyselect_1.1.1   rlang_0.4.11      
 [67] DiceDesign_1.9     later_1.3.0        cachem_1.0.6      
 [70] munsell_0.5.0      cellranger_1.1.0   tools_4.1.1       
 [73] cli_3.0.1          generics_0.1.0     gifski_1.4.3-1    
 [76] evaluate_0.14      fastmap_1.1.0      ragg_1.1.3        
 [79] yaml_2.2.1         rematch2_2.1.2     bit64_4.0.5       
 [82] knitr_1.34         fs_1.5.0           nlme_3.1-152      
 [85] future_1.22.1      whisker_0.4        R.oo_1.24.0       
 [88] xml2_1.3.2         compiler_4.1.1     rstudioapi_0.13   
 [91] curl_4.3.2         e1071_1.7-8        reprex_2.0.1      
 [94] lhs_1.1.3          tweenr_1.0.2       bslib_0.3.0       
 [97] stringi_1.7.4      highr_0.9          gdtools_0.2.3     
[100] hrbrthemes_0.8.0   lattice_0.20-44    Matrix_1.3-4      
[103] styler_1.6.1       classInt_0.4-3     conflicted_1.0.4  
[106] vctrs_0.3.8        pillar_1.6.2       lifecycle_1.0.1   
[109] furrr_0.2.3        jquerylib_0.1.4    httpuv_1.6.3      
[112] R6_2.5.1           promises_1.2.0.1   KernSmooth_2.23-20
[115] gridExtra_2.3      parallelly_1.28.1  codetools_0.2-18  
[118] MASS_7.3-54        assertthat_0.2.1   rprojroot_2.0.2   
[121] withr_2.4.2        mgcv_1.8-36        parallel_4.1.1    
[124] hms_1.1.0          grid_4.1.1         rpart_4.1-15      
[127] timeDate_3043.102  class_7.3-19       snakecase_0.11.0  
[130] rmarkdown_2.11     git2r_0.28.0       pROC_1.18.0