Challenge 9 Solution

Creating a function
Author

Susannah Reed Poland

Published

June 12, 2023

library(tidyverse)
library(ggplot2)
library(lubridate)
library(readxl)

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

Create a function that reads in and cleans a dataset

I chose to create a function that changes a column of year and quarter characters to dates, and removes the old column.

#create a function called "read_debt", f is the file name and by default is false
read_debt<-function(f){
#read in the data file
  d<-read_excel(f)%>%
#change the "year and quarter" to a date format
    mutate(date_orig = parse_date_time(`Year and Quarter`, orders="yq"))%>%
#remove the old column
  select(-`Year and Quarter`)
  return(d)
}

Now we can apply this to the “Debt in Trillions” dataset:

#apply function
debt_date<-read_debt("_data/debt_in_trillions.xlsx")

#check it out!
debt_date
ABCDEFGHIJ0123456789
Mortgage
<dbl>
HE Revolving
<dbl>
Auto Loan
<dbl>
Credit Card
<dbl>
Student Loan
<dbl>
Other
<dbl>
Total
<dbl>
date_orig
<dttm>
4.9420.24200.64100.68800.24070000.47767.231302003-01-01
5.0800.26000.62200.69300.24290000.48607.383902003-04-01
5.1830.26900.68400.69300.24880000.47737.555102003-07-01
5.6600.30200.70400.69800.25290000.44868.065502003-10-01
5.8400.32800.72000.69500.25980000.44658.289302004-01-01
5.9670.36700.74300.69700.26290000.42318.460002004-04-01
6.2100.42600.75100.70600.33000000.41008.833002004-07-01
6.3600.46800.72800.71700.34570000.42299.041602004-10-01
6.5120.50200.72500.71000.36360000.39419.206702005-01-01
6.6960.52800.77400.71700.37440000.40249.491802005-04-01

Et voila!