challenge_4
abc_poll
eggs
fed_rates
hotel_bookings
debt
More data wrangling: pivoting
Author

Calvin Cuff

Published

January 2, 2024

Code
library(here)
library(readxl)
library(tidyverse)

knitr::opts_chunk$set(echo = TRUE, warning=FALSE, message=FALSE)

Challenge Overview

Today’s challenge is to:

  1. read in a data set, and describe the data set using both words and any supporting information (e.g., tables, etc)
  2. tidy data (as needed, including sanity checks)
  3. identify variables that need to be mutated
  4. mutate variables and sanity check all mutations

Read in data

Read in one (or more) of the following datasets, using the correct R package and command.

  • abc_poll.csv ⭐
  • poultry_tidy.xlsx or organiceggpoultry.xls⭐⭐
  • FedFundsRate.csv⭐⭐⭐
  • hotel_bookings.csv⭐⭐⭐⭐
  • debt_in_trillions.xlsx ⭐⭐⭐⭐⭐
Code
debt <- read_excel(here("data", "debt_in_trillions.xlsx"))
head(debt)
# A tibble: 6 × 8
  `Year and Quarter` Mortgage `HE Revolving` `Auto Loan` `Credit Card`
  <chr>                 <dbl>          <dbl>       <dbl>         <dbl>
1 03:Q1                  4.94          0.242       0.641         0.688
2 03:Q2                  5.08          0.26        0.622         0.693
3 03:Q3                  5.18          0.269       0.684         0.693
4 03:Q4                  5.66          0.302       0.704         0.698
5 04:Q1                  5.84          0.328       0.72          0.695
6 04:Q2                  5.97          0.367       0.743         0.697
# ℹ 3 more variables: `Student Loan` <dbl>, Other <dbl>, Total <dbl>

Briefly describe the data

Code
dim(debt)
[1] 74  8
Code
colnames(debt)
[1] "Year and Quarter" "Mortgage"         "HE Revolving"     "Auto Loan"       
[5] "Credit Card"      "Student Loan"     "Other"            "Total"           

This data set consists of 74 rows and 8 columns describing the debt in trillions of types of loans by year and quarter from 2003 to 2021.

Tidy Data (as needed)

Is your data already tidy, or is there work to be done? Be sure to anticipate your end result to provide a sanity check, and document your work here.

To tidy this data we can omit the “total” column as that is repetitive of the other columns. We should also rename the columns to something easier to work with. The year and quarter are also stored together so we must separate them into their respective columns.

Code
debt_tidy <- debt %>%
  # Omit column 'Total'
  select(!Total) %>%
  # Rename columns
  rename(mortgage = Mortgage,
         he_revolving = 'HE Revolving',
         auto_loan = 'Auto Loan',
         credit_card = 'Credit Card',
         student_loan = 'Student Loan',
         other = Other
         ) %>%
  # Separate year and quarter
  separate('Year and Quarter', into=c("year", "quarter"), sep=":")

# Fill in full year
debt_tidy$year <- paste0('20', debt_tidy$year)

Any additional comments?

Identify variables that need to be mutated

Are there any variables that require mutation to be usable in your analysis stream? For example, are all time variables correctly coded as dates? Are all string variables reduced and cleaned to sensible categories? Do you need to turn any variables into factors and reorder for ease of graphics and visualization?

Document your work here.

This data would be easier to work with if we pivoted it longer and classified the type of debt in one column and the corresponding amount of debt in another. Since we are combining the data of 6 columns, we should see the number of rows increased by a factor of 6.

Code
debt_longer <- debt_tidy %>%
  pivot_longer(cols = 3:8  , names_to = "loan_type", values_to = "debt_in_trillions")

head(debt_longer)
# A tibble: 6 × 4
  year  quarter loan_type    debt_in_trillions
  <chr> <chr>   <chr>                    <dbl>
1 2003  Q1      mortgage                 4.94 
2 2003  Q1      he_revolving             0.242
3 2003  Q1      auto_loan                0.641
4 2003  Q1      credit_card              0.688
5 2003  Q1      student_loan             0.241
6 2003  Q1      other                    0.478
Code
dim(debt_longer)
[1] 444   4

We can now easily group and calculate the totals for year or by quarter or investigate the proportional relationships of types of loans.

We can see the total debt in trillions by grouping by year below.

Code
debt_longer %>%
  group_by(year) %>%
  summarise(total=sum(debt_in_trillions)) %>%
  ungroup
# A tibble: 19 × 2
   year  total
   <chr> <dbl>
 1 2003   30.2
 2 2004   34.6
 3 2005   38.5
 4 2006   43.6
 5 2007   47.8
 6 2008   50.5
 7 2009   49.4
 8 2010   47.6
 9 2011   46.7
10 2012   45.5
11 2013   45.2
12 2014   46.8
13 2015   47.9
14 2016   49.5
15 2017   51.7
16 2018   53.6
17 2019   55.6
18 2020   57.5
19 2021   29.6

Or we could group by year and loan type.

Code
debt_longer %>%
  group_by(year, loan_type) %>%
    summarise(year_total=sum(debt_in_trillions), quarter_avg = mean(debt_in_trillions))
# A tibble: 114 × 4
# Groups:   year [19]
   year  loan_type    year_total quarter_avg
   <chr> <chr>             <dbl>       <dbl>
 1 2003  auto_loan         2.65        0.663
 2 2003  credit_card       2.77        0.693
 3 2003  he_revolving      1.07        0.268
 4 2003  mortgage         20.9         5.22 
 5 2003  other             1.89        0.472
 6 2003  student_loan      0.985       0.246
 7 2004  auto_loan         2.94        0.736
 8 2004  credit_card       2.82        0.704
 9 2004  he_revolving      1.59        0.397
10 2004  mortgage         24.4         6.09 
# ℹ 104 more rows

Any additional comments?

There are also probably some more advanced groupings and statistical insights to be derived about the yearly percentage makeup of loan types and their respective debts based on what analysis was needed.