library(tidyverse)
library(ggplot2)
library(lubridate)
library(readxl)
::opts_chunk$set(echo = TRUE, warning=FALSE, message=FALSE) knitr
Challenge 9 Solution
Creating a function
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
<-function(f){
read_debt#read in the data file
<-read_excel(f)%>%
d#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
<-read_debt("_data/debt_in_trillions.xlsx")
debt_date
#check it out!
debt_date
Mortgage <dbl> | HE Revolving <dbl> | Auto Loan <dbl> | Credit Card <dbl> | Student Loan <dbl> | Other <dbl> | Total <dbl> | date_orig <dttm> |
---|---|---|---|---|---|---|---|
4.942 | 0.2420 | 0.6410 | 0.6880 | 0.2407000 | 0.4776 | 7.23130 | 2003-01-01 |
5.080 | 0.2600 | 0.6220 | 0.6930 | 0.2429000 | 0.4860 | 7.38390 | 2003-04-01 |
5.183 | 0.2690 | 0.6840 | 0.6930 | 0.2488000 | 0.4773 | 7.55510 | 2003-07-01 |
5.660 | 0.3020 | 0.7040 | 0.6980 | 0.2529000 | 0.4486 | 8.06550 | 2003-10-01 |
5.840 | 0.3280 | 0.7200 | 0.6950 | 0.2598000 | 0.4465 | 8.28930 | 2004-01-01 |
5.967 | 0.3670 | 0.7430 | 0.6970 | 0.2629000 | 0.4231 | 8.46000 | 2004-04-01 |
6.210 | 0.4260 | 0.7510 | 0.7060 | 0.3300000 | 0.4100 | 8.83300 | 2004-07-01 |
6.360 | 0.4680 | 0.7280 | 0.7170 | 0.3457000 | 0.4229 | 9.04160 | 2004-10-01 |
6.512 | 0.5020 | 0.7250 | 0.7100 | 0.3636000 | 0.3941 | 9.20670 | 2005-01-01 |
6.696 | 0.5280 | 0.7740 | 0.7170 | 0.3744000 | 0.4024 | 9.49180 | 2005-04-01 |
Et voila!