-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathocs-healthexpenditure.tex
2803 lines (2370 loc) · 125 KB
/
ocs-healthexpenditure.tex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
\documentclass[]{article}
\usepackage{lmodern}
\usepackage{amssymb,amsmath}
\usepackage{ifxetex,ifluatex}
\usepackage{fixltx2e} % provides \textsubscript
\ifnum 0\ifxetex 1\fi\ifluatex 1\fi=0 % if pdftex
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\else % if luatex or xelatex
\ifxetex
\usepackage{mathspec}
\else
\usepackage{fontspec}
\fi
\defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase}
\fi
% use upquote if available, for straight quotes in verbatim environments
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
% use microtype if available
\IfFileExists{microtype.sty}{%
\usepackage{microtype}
\UseMicrotypeSet[protrusion]{basicmath} % disable protrusion for tt fonts
}{}
\usepackage[margin=1in]{geometry}
\usepackage{hyperref}
\hypersetup{unicode=true,
pdftitle={OpenCaseStudies - Health Expenditure},
pdfborder={0 0 0},
breaklinks=true}
\urlstyle{same} % don't use monospace font for urls
\usepackage{color}
\usepackage{fancyvrb}
\newcommand{\VerbBar}{|}
\newcommand{\VERB}{\Verb[commandchars=\\\{\}]}
\DefineVerbatimEnvironment{Highlighting}{Verbatim}{commandchars=\\\{\}}
% Add ',fontsize=\small' for more characters per line
\usepackage{framed}
\definecolor{shadecolor}{RGB}{248,248,248}
\newenvironment{Shaded}{\begin{snugshade}}{\end{snugshade}}
\newcommand{\AlertTok}[1]{\textcolor[rgb]{0.94,0.16,0.16}{#1}}
\newcommand{\AnnotationTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textbf{\textit{#1}}}}
\newcommand{\AttributeTok}[1]{\textcolor[rgb]{0.77,0.63,0.00}{#1}}
\newcommand{\BaseNTok}[1]{\textcolor[rgb]{0.00,0.00,0.81}{#1}}
\newcommand{\BuiltInTok}[1]{#1}
\newcommand{\CharTok}[1]{\textcolor[rgb]{0.31,0.60,0.02}{#1}}
\newcommand{\CommentTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textit{#1}}}
\newcommand{\CommentVarTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textbf{\textit{#1}}}}
\newcommand{\ConstantTok}[1]{\textcolor[rgb]{0.00,0.00,0.00}{#1}}
\newcommand{\ControlFlowTok}[1]{\textcolor[rgb]{0.13,0.29,0.53}{\textbf{#1}}}
\newcommand{\DataTypeTok}[1]{\textcolor[rgb]{0.13,0.29,0.53}{#1}}
\newcommand{\DecValTok}[1]{\textcolor[rgb]{0.00,0.00,0.81}{#1}}
\newcommand{\DocumentationTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textbf{\textit{#1}}}}
\newcommand{\ErrorTok}[1]{\textcolor[rgb]{0.64,0.00,0.00}{\textbf{#1}}}
\newcommand{\ExtensionTok}[1]{#1}
\newcommand{\FloatTok}[1]{\textcolor[rgb]{0.00,0.00,0.81}{#1}}
\newcommand{\FunctionTok}[1]{\textcolor[rgb]{0.00,0.00,0.00}{#1}}
\newcommand{\ImportTok}[1]{#1}
\newcommand{\InformationTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textbf{\textit{#1}}}}
\newcommand{\KeywordTok}[1]{\textcolor[rgb]{0.13,0.29,0.53}{\textbf{#1}}}
\newcommand{\NormalTok}[1]{#1}
\newcommand{\OperatorTok}[1]{\textcolor[rgb]{0.81,0.36,0.00}{\textbf{#1}}}
\newcommand{\OtherTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{#1}}
\newcommand{\PreprocessorTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textit{#1}}}
\newcommand{\RegionMarkerTok}[1]{#1}
\newcommand{\SpecialCharTok}[1]{\textcolor[rgb]{0.00,0.00,0.00}{#1}}
\newcommand{\SpecialStringTok}[1]{\textcolor[rgb]{0.31,0.60,0.02}{#1}}
\newcommand{\StringTok}[1]{\textcolor[rgb]{0.31,0.60,0.02}{#1}}
\newcommand{\VariableTok}[1]{\textcolor[rgb]{0.00,0.00,0.00}{#1}}
\newcommand{\VerbatimStringTok}[1]{\textcolor[rgb]{0.31,0.60,0.02}{#1}}
\newcommand{\WarningTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textbf{\textit{#1}}}}
\usepackage{longtable,booktabs}
\usepackage{graphicx,grffile}
\makeatletter
\def\maxwidth{\ifdim\Gin@nat@width>\linewidth\linewidth\else\Gin@nat@width\fi}
\def\maxheight{\ifdim\Gin@nat@height>\textheight\textheight\else\Gin@nat@height\fi}
\makeatother
% Scale images if necessary, so that they will not overflow the page
% margins by default, and it is still possible to overwrite the defaults
% using explicit options in \includegraphics[width, height, ...]{}
\setkeys{Gin}{width=\maxwidth,height=\maxheight,keepaspectratio}
\IfFileExists{parskip.sty}{%
\usepackage{parskip}
}{% else
\setlength{\parindent}{0pt}
\setlength{\parskip}{6pt plus 2pt minus 1pt}
}
\setlength{\emergencystretch}{3em} % prevent overfull lines
\providecommand{\tightlist}{%
\setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}}
\setcounter{secnumdepth}{0}
% Redefines (sub)paragraphs to behave more like sections
\ifx\paragraph\undefined\else
\let\oldparagraph\paragraph
\renewcommand{\paragraph}[1]{\oldparagraph{#1}\mbox{}}
\fi
\ifx\subparagraph\undefined\else
\let\oldsubparagraph\subparagraph
\renewcommand{\subparagraph}[1]{\oldsubparagraph{#1}\mbox{}}
\fi
%%% Use protect on footnotes to avoid problems with footnotes in titles
\let\rmarkdownfootnote\footnote%
\def\footnote{\protect\rmarkdownfootnote}
%%% Change title format to be more compact
\usepackage{titling}
% Create subtitle command for use in maketitle
\providecommand{\subtitle}[1]{
\posttitle{
\begin{center}\large#1\end{center}
}
}
\setlength{\droptitle}{-2em}
\title{OpenCaseStudies - Health Expenditure}
\pretitle{\vspace{\droptitle}\centering\huge}
\posttitle{\par}
\author{}
\preauthor{}\postauthor{}
\date{}
\predate{}\postdate{}
\begin{document}
\maketitle
{
\setcounter{tocdepth}{2}
\tableofcontents
}
\includegraphics[width=1\linewidth]{./img/SummaryPlot}
\hypertarget{motivation}{%
\section{Motivation}\label{motivation}}
Health policy in the States is complicated, and several forms of
healthcare coverage existed in the United States of America, including
both federal government-led healthcare policy, and private insurance
company. Before making any inference about the relationship between
health condition and health policy, it is important for us to have a
general idea about healthcare economics in the States. Thus, we are
interested in getting sense of the health expenditure, including
healthcare coverage and healthcare spending, across States. More
specifically, the questions are:
\begin{enumerate}
\def\labelenumi{\arabic{enumi}.}
\tightlist
\item
Is there a relationship between healthcare coverage and healthcare
spending in the United States?\\
\item
How does the spending distribution change across geographic regions in
the United States?\\
\item
Does the relationship between healthcare coverage and healthcare
spending in the United States change from 2013 to 2014?
\end{enumerate}
In this case study, we'll walk you through collecting data, importing
data, cleaning data, wrangling data, and visualizing the data, using
well-established and commonly used packages, including
\texttt{datasets}, \texttt{tidyr}, \texttt{dplyr}, \texttt{ggplot2}, and
\texttt{ggrepel}.
\hypertarget{what-is-the-data}{%
\section{What is the data?}\label{what-is-the-data}}
\includegraphics[width=0.9\linewidth]{https://aspe.hhs.gov/system/files/images-reports-basic/70441/fig1}
\href{https://aspe.hhs.gov/basic-report/overview-uninsured-united-states-summary-2011-current-population-survey}{Image
source from US Department of Health and Human Services}
\hypertarget{healthcare-data}{%
\subsection{Healthcare data}\label{healthcare-data}}
We will be using the data from the \href{https://www.kff.org}{Henry J
Kaiser Family Foundation (KFF)}.
\begin{itemize}
\tightlist
\item
\href{https://www.kff.org/other/state-indicator/total-population/}{Health
Insurance Coverage of the Total Population} - Includes years 2013-2016
\item
\href{https://www.kff.org/other/state-indicator/health-care-expenditures-by-state-of-residence-in-millions/}{Health
Care Expenditures by State of Residence (in millions)} - Includes
years 1991-2014
\end{itemize}
We have downloaded, re-named and saved these files in the
\href{https://github.com/opencasestudies/ocs-healthexpenditure}{GitHub
repository} under the \texttt{data/KFF/} directory.
Now, before we dig into the data analysis, we need to introduce a set of
R packages that we will use to analyze the data.
\hypertarget{data-import}{%
\section{Data Import}\label{data-import}}
\hypertarget{introduction-to-tidy-data}{%
\subsection{Introduction to ``Tidy
data''}\label{introduction-to-tidy-data}}
The \href{https://www.tidyverse.org}{tidyverse} is \emph{``an
opinionated collection of R packages designed for data science. All
packages share an underlying philosophy and common APIs.''}
Another way of putting it is that it's a set of packages that are useful
specifically for data manipulation, exploration and visualization with a
common philosophy.
\hypertarget{what-is-this-common-philosophy}{%
\paragraph{What is this common
philosophy?}\label{what-is-this-common-philosophy}}
The common philosophy is called \emph{``tidy''} data. It is a standard
way of mapping the meaning of a dataset to its structure.
In \emph{tidy} data:
\begin{itemize}
\tightlist
\item
Each variable forms a column.
\item
Each observation forms a row.
\item
Each type of observational unit forms a table.
\end{itemize}
\includegraphics[width=0.95\linewidth]{http://r4ds.had.co.nz/images/tidy-1}
Below, we are interested in transforming the table on the right to the
the table on the left, which is considered ``tidy''.
\includegraphics[width=0.95\linewidth]{http://r4ds.had.co.nz/images/tidy-9}
Working with tidy data is useful because it creates a structured way of
organizing data values within a data set. This makes the data analysis
process more efficient and simplifies the development of data analysis
tools that work together. In this way, you can focus on the problem you
are investigating, rather than the uninteresting logistics of data.
\hypertarget{what-is-in-the-tidyverse}{%
\subsubsection{\texorpdfstring{1. What is in the
\texttt{tidyverse}?}{1. What is in the tidyverse?}}\label{what-is-in-the-tidyverse}}
We can install and load the set of R packages using
\texttt{install.packages("tidyverse")} function.
When we load the tidyverse package using \texttt{library(tidyverse)},
there are six core R packages that load:
\begin{itemize}
\tightlist
\item
\href{http://readr.tidyverse.org}{readr}, for data import.
\item
\href{http://tidyr.tidyverse.org}{tidyr}, for data tidying.
\item
\href{http://dplyr.tidyverse.org}{dplyr}, for data wrangling.
\item
\href{http://ggplot2.tidyverse.org}{ggplot2}, for data visualisation.
\item
\href{http://purrr.tidyverse.org}{purrr}, for functional programming.
\item
\href{http://tibble.tidyverse.org}{tibble}, for tibbles, a modern
re-imagining of data frames.
\end{itemize}
Here, we load in the tidyverse.
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{library}\NormalTok{(tidyverse)}
\end{Highlighting}
\end{Shaded}
These packages are highlighted in bold here:
\includegraphics[width=0.95\linewidth]{https://rviews.rstudio.com/post/2017-06-09-What-is-the-tidyverse_files/tidyverse1}
Because these packages all share the ``tidy'' philosophy, the data
analysis workflow is easier as you move from package to package.
Here, we will focus on the \texttt{readr}, \texttt{tidyr} and
\texttt{dplyr} R packages to import data, to transform data to the
``tidy'' format, and to wrangle data.
Next, we will give a brief description of the features in each of these
packages.
There are several base R functions that allow you read in data into R,
which you may be familiar with such as \texttt{read.table()},
\texttt{read.csv()}, and \texttt{read.delim()}. Instead of using these,
we will use the functions in the
\href{https://readr.tidyverse.org/articles/readr.html}{readr} R package.
The main reasons for this are
\begin{enumerate}
\def\labelenumi{\arabic{enumi}.}
\tightlist
\item
Compared to equivalent base R functions, the functions in
\texttt{readr} are around 10x faster.
\item
You can specify the column types (e.g character, integer, double,
logical, date, time, etc)
\item
All parsing problems are recorded in a data frame.
\end{enumerate}
\hypertarget{read-data-using-the-readr-r-package}{%
\subsection{\texorpdfstring{Read data using the \texttt{readr} R
package}{Read data using the readr R package}}\label{read-data-using-the-readr-r-package}}
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{library}\NormalTok{(readr)}
\end{Highlighting}
\end{Shaded}
The main functions in \texttt{readr} are:
\begin{longtable}[]{@{}ll@{}}
\toprule
\begin{minipage}[b]{0.03\columnwidth}\raggedright
\texttt{readr} functions\strut
\end{minipage} & \begin{minipage}[b]{0.91\columnwidth}\raggedright
Description\strut
\end{minipage}\tabularnewline
\midrule
\endhead
\begin{minipage}[t]{0.03\columnwidth}\raggedright
\texttt{read\_delim()}\strut
\end{minipage} & \begin{minipage}[t]{0.91\columnwidth}\raggedright
reads in a flat file data with a given character to separate
fields\strut
\end{minipage}\tabularnewline
\begin{minipage}[t]{0.03\columnwidth}\raggedright
\texttt{read\_csv()}\strut
\end{minipage} & \begin{minipage}[t]{0.91\columnwidth}\raggedright
reads in a CSV file\strut
\end{minipage}\tabularnewline
\begin{minipage}[t]{0.03\columnwidth}\raggedright
\texttt{read\_tsv()}\strut
\end{minipage} & \begin{minipage}[t]{0.91\columnwidth}\raggedright
reads in a file with values separated by tabs\strut
\end{minipage}\tabularnewline
\begin{minipage}[t]{0.03\columnwidth}\raggedright
\texttt{read\_lines()}\strut
\end{minipage} & \begin{minipage}[t]{0.91\columnwidth}\raggedright
reads only a certain number of lines from the file\strut
\end{minipage}\tabularnewline
\begin{minipage}[t]{0.03\columnwidth}\raggedright
\texttt{read\_file()}\strut
\end{minipage} & \begin{minipage}[t]{0.91\columnwidth}\raggedright
reads a complete file into a string\strut
\end{minipage}\tabularnewline
\begin{minipage}[t]{0.03\columnwidth}\raggedright
\texttt{write\_csv()}\strut
\end{minipage} & \begin{minipage}[t]{0.91\columnwidth}\raggedright
writes data frame to CSV\strut
\end{minipage}\tabularnewline
\bottomrule
\end{longtable}
A useful cheatsheet for the functions in the \texttt{readr} package can
be found on RStudio's website:
\includegraphics{https://www.rstudio.com/wp-content/uploads/2018/08/data-import.png}
\hypertarget{read-in-data}{%
\subsubsection{1. Read in data}\label{read-in-data}}
\hypertarget{read-in-health-healthcare-coverage-data}{%
\paragraph{Read in health healthcare coverage
data}\label{read-in-health-healthcare-coverage-data}}
Let's try reading in some data. We will begin by reading in the
\texttt{healthcare-coverage.csv} data.
If we want to see what the header of the file looks like, we can use the
\texttt{read\_lines()} function to peak at the first few lines.
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{read_lines}\NormalTok{(}\DataTypeTok{file =} \StringTok{"./data/KFF/healthcare-coverage.csv"}\NormalTok{, }\DataTypeTok{n_max =} \DecValTok{10}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
[1] "\"Title: Health Insurance Coverage of the Total Population | The Henry J. Kaiser Family Foundation\""
[2] "\"Timeframe: 2013 - 2016\""
[3] "\"Location\",\"2013__Employer\",\"2013__Non-Group\",\"2013__Medicaid\",\"2013__Medicare\",\"2013__Other Public\",\"2013__Uninsured\",\"2013__Total\",\"2014__Employer\",\"2014__Non-Group\",\"2014__Medicaid\",\"2014__Medicare\",\"2014__Other Public\",\"2014__Uninsured\",\"2014__Total\",\"2015__Employer\",\"2015__Non-Group\",\"2015__Medicaid\",\"2015__Medicare\",\"2015__Other Public\",\"2015__Uninsured\",\"2015__Total\",\"2016__Employer\",\"2016__Non-Group\",\"2016__Medicaid\",\"2016__Medicare\",\"2016__Other Public\",\"2016__Uninsured\",\"2016__Total\""
[4] "\"United States\",\"155696900\",\"13816000\",\"54919100\",\"40876300\",\"6295400\",\"41795100\",\"313401200\",\"154347500\",\"19313000\",\"61650400\",\"41896500\",\"5985000\",\"32967500\",\"316159900\",\"155965800\",\"21816500\",\"62384500\",\"43308400\",\"6422300\",\"28965900\",\"318868500\",\"157381500\",\"21884400\",\"62303400\",\"44550200\",\"6192200\",\"28051900\",\"320372000\""
[5] "\"Alabama\",\"2126500\",\"174200\",\"869700\",\"783000\",\"85600\",\"724800\",\"4763900\",\"2202800\",\"288900\",\"891900\",\"718400\",\"143900\",\"522200\",\"4768000\",\"2218000\",\"291500\",\"911400\",\"719100\",\"174600\",\"519400\",\"4833900\",\"2263800\",\"262400\",\"997000\",\"761200\",\"128800\",\"420800\",\"4834100\""
[6] "\"Alaska\",\"364900\",\"24000\",\"95000\",\"55200\",\"60600\",\"102200\",\"702000\",\"345300\",\"26800\",\"130100\",\"55300\",\"37300\",\"100800\",\"695700\",\"355700\",\"22300\",\"128100\",\"60900\",\"47700\",\"90500\",\"705300\",\"324400\",\"20300\",\"145400\",\"68200\",\"55600\",\"96900\",\"710800\""
[7] "\"Arizona\",\"2883800\",\"170800\",\"1346100\",\"842000\",\"N/A\",\"1223000\",\"6603100\",\"2835200\",\"333500\",\"1639400\",\"911100\",\"N/A\",\"827100\",\"6657200\",\"2766500\",\"278400\",\"1711500\",\"949000\",\"189300\",\"844800\",\"6739500\",\"3010700\",\"377000\",\"1468400\",\"1028000\",\"172500\",\"833700\",\"6890200\""
[8] "\"Arkansas\",\"1128800\",\"155600\",\"600800\",\"515200\",\"67600\",\"436800\",\"2904800\",\"1176500\",\"231700\",\"639200\",\"479400\",\"82000\",\"287200\",\"2896000\",\"1293700\",\"200200\",\"641400\",\"484500\",\"63700\",\"268400\",\"2953000\",\"1290900\",\"252900\",\"618600\",\"490000\",\"67500\",\"225500\",\"2945300\""
[9] "\"California\",\"17747300\",\"1986400\",\"8344800\",\"3828500\",\"675400\",\"5594100\",\"38176400\",\"17703700\",\"2778800\",\"9618800\",\"4049000\",\"634400\",\"3916700\",\"38701300\",\"17718300\",\"3444200\",\"10138100\",\"4080100\",\"752700\",\"2980600\",\"39113900\",\"18116200\",\"3195400\",\"9853800\",\"4436000\",\"556100\",\"3030800\",\"39188300\""
[10] "\"Colorado\",\"2852500\",\"426300\",\"697300\",\"549700\",\"118100\",\"654000\",\"5297800\",\"2489400\",\"397900\",\"1053700\",\"619500\",\"214000\",\"602900\",\"5377400\",\"2706000\",\"346900\",\"1036600\",\"708000\",\"148000\",\"475700\",\"5421300\",\"2872600\",\"370000\",\"855800\",\"692400\",\"190100\",\"528400\",\"5509200\""
\end{verbatim}
It looks like the first two lines are descriptive and are not useful. We
will tell R to skip reading these in using the \texttt{skip} argument in
\texttt{read\_csv()}. The third line looks like it contains the column
names and starting on the fourth line is where the data starts.
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{coverage <-}\StringTok{ }\KeywordTok{read_csv}\NormalTok{(}\StringTok{"./data/KFF/healthcare-coverage.csv"}\NormalTok{, }
\DataTypeTok{skip =} \DecValTok{2}\NormalTok{, }\DataTypeTok{col_names =} \OtherTok{TRUE}\NormalTok{)}
\KeywordTok{head}\NormalTok{(coverage)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
# A tibble: 6 x 29
Location `2013__Employer` `2013__Non-Grou~ `2013__Medicaid`
<chr> <dbl> <dbl> <dbl>
1 United ~ 155696900 13816000 54919100
2 Alabama 2126500 174200 869700
3 Alaska 364900 24000 95000
4 Arizona 2883800 170800 1346100
5 Arkansas 1128800 155600 600800
6 Califor~ 17747300 1986400 8344800
# ... with 25 more variables: `2013__Medicare` <dbl>, `2013__Other
# Public` <chr>, `2013__Uninsured` <dbl>, `2013__Total` <dbl>,
# `2014__Employer` <dbl>, `2014__Non-Group` <dbl>,
# `2014__Medicaid` <dbl>, `2014__Medicare` <dbl>, `2014__Other
# Public` <chr>, `2014__Uninsured` <dbl>, `2014__Total` <dbl>,
# `2015__Employer` <dbl>, `2015__Non-Group` <dbl>,
# `2015__Medicaid` <dbl>, `2015__Medicare` <dbl>, `2015__Other
# Public` <chr>, `2015__Uninsured` <dbl>, `2015__Total` <dbl>,
# `2016__Employer` <dbl>, `2016__Non-Group` <dbl>,
# `2016__Medicaid` <dbl>, `2016__Medicare` <dbl>, `2016__Other
# Public` <chr>, `2016__Uninsured` <dbl>, `2016__Total` <dbl>
\end{verbatim}
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{tail}\NormalTok{(coverage)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
# A tibble: 6 x 29
Location `2013__Employer` `2013__Non-Grou~ `2013__Medicaid`
<chr> <dbl> <dbl> <dbl>
1 <NA> NA NA NA
2 *Uninsu~ NA NA NA
3 <NA> NA NA NA
4 For exa~ NA NA NA
5 <NA> NA NA NA
6 *N/A*: ~ NA NA NA
# ... with 25 more variables: `2013__Medicare` <dbl>, `2013__Other
# Public` <chr>, `2013__Uninsured` <dbl>, `2013__Total` <dbl>,
# `2014__Employer` <dbl>, `2014__Non-Group` <dbl>,
# `2014__Medicaid` <dbl>, `2014__Medicare` <dbl>, `2014__Other
# Public` <chr>, `2014__Uninsured` <dbl>, `2014__Total` <dbl>,
# `2015__Employer` <dbl>, `2015__Non-Group` <dbl>,
# `2015__Medicaid` <dbl>, `2015__Medicare` <dbl>, `2015__Other
# Public` <chr>, `2015__Uninsured` <dbl>, `2015__Total` <dbl>,
# `2016__Employer` <dbl>, `2016__Non-Group` <dbl>,
# `2016__Medicaid` <dbl>, `2016__Medicare` <dbl>, `2016__Other
# Public` <chr>, `2016__Uninsured` <dbl>, `2016__Total` <dbl>
\end{verbatim}
It looks like we now have the right header, but there are a bunch of NAs
in the end of the data frame because most of it isn't useful data.
Let's take a closer look at the last 30 lines
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{tail}\NormalTok{(coverage, }\DataTypeTok{n=}\DecValTok{30}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
# A tibble: 30 x 29
Location `2013__Employer` `2013__Non-Grou~ `2013__Medicaid`
<chr> <dbl> <dbl> <dbl>
1 Washing~ 3541600 309000 1026800
2 West Vi~ 841300 42600 382500
3 Wiscons~ 3154500 225300 907600
4 Wyoming 305900 19500 74200
5 Notes NA NA NA
6 The maj~ NA NA NA
7 <NA> NA NA NA
8 "In thi~ NA NA NA
9 <NA> NA NA NA
10 Data ex~ NA NA NA
# ... with 20 more rows, and 25 more variables: `2013__Medicare` <dbl>,
# `2013__Other Public` <chr>, `2013__Uninsured` <dbl>,
# `2013__Total` <dbl>, `2014__Employer` <dbl>, `2014__Non-Group` <dbl>,
# `2014__Medicaid` <dbl>, `2014__Medicare` <dbl>, `2014__Other
# Public` <chr>, `2014__Uninsured` <dbl>, `2014__Total` <dbl>,
# `2015__Employer` <dbl>, `2015__Non-Group` <dbl>,
# `2015__Medicaid` <dbl>, `2015__Medicare` <dbl>, `2015__Other
# Public` <chr>, `2015__Uninsured` <dbl>, `2015__Total` <dbl>,
# `2016__Employer` <dbl>, `2016__Non-Group` <dbl>,
# `2016__Medicaid` <dbl>, `2016__Medicare` <dbl>, `2016__Other
# Public` <chr>, `2016__Uninsured` <dbl>, `2016__Total` <dbl>
\end{verbatim}
It looks like there is a line with a string \texttt{Notes} in it and
everything below that line should not be read in. We can use the
\texttt{n\_max} argument here.
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{coverage <-}\StringTok{ }\KeywordTok{read_csv}\NormalTok{(}\StringTok{"./data/KFF/healthcare-coverage.csv"}\NormalTok{, }
\DataTypeTok{skip =} \DecValTok{2}\NormalTok{, }\DataTypeTok{col_names =} \OtherTok{TRUE}\NormalTok{)}
\NormalTok{coverage <-}\StringTok{ }\KeywordTok{read_csv}\NormalTok{(}\StringTok{"./data/KFF/healthcare-coverage.csv"}\NormalTok{, }
\DataTypeTok{skip =} \DecValTok{2}\NormalTok{, }\DataTypeTok{col_names =} \OtherTok{TRUE}\NormalTok{,}
\DataTypeTok{n_max =} \KeywordTok{which}\NormalTok{(coverage}\OperatorTok{$}\NormalTok{Location }\OperatorTok{==}\StringTok{ "Notes"}\NormalTok{)}\OperatorTok{-}\DecValTok{1}\NormalTok{)}
\KeywordTok{tail}\NormalTok{(coverage)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
# A tibble: 6 x 29
Location `2013__Employer` `2013__Non-Grou~ `2013__Medicaid`
<chr> <dbl> <dbl> <dbl>
1 Vermont 317700 26200 123400
2 Virginia 4661600 364800 773200
3 Washing~ 3541600 309000 1026800
4 West Vi~ 841300 42600 382500
5 Wiscons~ 3154500 225300 907600
6 Wyoming 305900 19500 74200
# ... with 25 more variables: `2013__Medicare` <dbl>, `2013__Other
# Public` <chr>, `2013__Uninsured` <dbl>, `2013__Total` <dbl>,
# `2014__Employer` <dbl>, `2014__Non-Group` <dbl>,
# `2014__Medicaid` <dbl>, `2014__Medicare` <dbl>, `2014__Other
# Public` <chr>, `2014__Uninsured` <dbl>, `2014__Total` <dbl>,
# `2015__Employer` <dbl>, `2015__Non-Group` <dbl>,
# `2015__Medicaid` <dbl>, `2015__Medicare` <dbl>, `2015__Other
# Public` <chr>, `2015__Uninsured` <dbl>, `2015__Total` <dbl>,
# `2016__Employer` <dbl>, `2016__Non-Group` <dbl>,
# `2016__Medicaid` <dbl>, `2016__Medicare` <dbl>, `2016__Other
# Public` <chr>, `2016__Uninsured` <dbl>, `2016__Total` <dbl>
\end{verbatim}
That's better!
\hypertarget{read-in-healthcare-spending-data}{%
\paragraph{Read in healthcare spending
data}\label{read-in-healthcare-spending-data}}
Now because we are also going to want to use in
\texttt{healthcare-spending.csv}, let's read it in now.
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{spending <-}\StringTok{ }\KeywordTok{read_csv}\NormalTok{(}\StringTok{"./data/KFF/healthcare-spending.csv"}\NormalTok{, }
\DataTypeTok{skip =} \DecValTok{2}\NormalTok{, }\DataTypeTok{col_names =} \OtherTok{TRUE}\NormalTok{)}
\NormalTok{spending <-}\StringTok{ }\KeywordTok{read_csv}\NormalTok{(}\StringTok{"./data/KFF/healthcare-spending.csv"}\NormalTok{, }
\DataTypeTok{skip =} \DecValTok{2}\NormalTok{, }\DataTypeTok{col_names =} \OtherTok{TRUE}\NormalTok{,}
\DataTypeTok{n_max =} \KeywordTok{which}\NormalTok{(spending}\OperatorTok{$}\NormalTok{Location }\OperatorTok{==}\StringTok{ "Notes"}\NormalTok{)}\OperatorTok{-}\DecValTok{1}\NormalTok{)}
\KeywordTok{tail}\NormalTok{(spending)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
# A tibble: 6 x 25
Location `1991__Total He~ `1992__Total He~ `1993__Total He~
<chr> <dbl> <dbl> <dbl>
1 Vermont 1330 1421 1522
2 Virginia 14829 15599 16634
3 Washing~ 12674 13859 14523
4 West Vi~ 4672 5159 5550
5 Wiscons~ 12694 13669 14636
6 Wyoming 1023 1067 1171
# ... with 21 more variables: `1994__Total Health Spending` <dbl>,
# `1995__Total Health Spending` <dbl>, `1996__Total Health
# Spending` <dbl>, `1997__Total Health Spending` <dbl>, `1998__Total
# Health Spending` <dbl>, `1999__Total Health Spending` <dbl>,
# `2000__Total Health Spending` <dbl>, `2001__Total Health
# Spending` <dbl>, `2002__Total Health Spending` <dbl>, `2003__Total
# Health Spending` <dbl>, `2004__Total Health Spending` <dbl>,
# `2005__Total Health Spending` <dbl>, `2006__Total Health
# Spending` <dbl>, `2007__Total Health Spending` <dbl>, `2008__Total
# Health Spending` <dbl>, `2009__Total Health Spending` <dbl>,
# `2010__Total Health Spending` <dbl>, `2011__Total Health
# Spending` <dbl>, `2012__Total Health Spending` <dbl>, `2013__Total
# Health Spending` <dbl>, `2014__Total Health Spending` <dbl>
\end{verbatim}
\hypertarget{take-a-glimpse-at-your-data}{%
\subsubsection{\texorpdfstring{2. Take a \texttt{glimpse()} at your
data}{2. Take a glimpse() at your data}}\label{take-a-glimpse-at-your-data}}
One last thing in this section. One way to look at our data would be to
use \texttt{head()} or \texttt{tail()}, as we just saw. Another one you
might have heard of is the \texttt{str()} function. One you might not
have heard of is the \texttt{glimpse()} function. It's used for a
special type of object in R called a \texttt{tibble}. Let's read the
help file to learn more.
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{?tibble}\OperatorTok{::}\NormalTok{tibble}
\end{Highlighting}
\end{Shaded}
It's kind of like \texttt{print()} where it shows you columns running
down the page. Let's try it out. If we look at our data, say the
\texttt{coverage} data frame, we see that it is not \emph{``tidy''}:
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{glimpse}\NormalTok{(coverage)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
Observations: 52
Variables: 29
$ Location <chr> "United States", "Alabama", "Alaska", "Ar...
$ `2013__Employer` <dbl> 155696900, 2126500, 364900, 2883800, 1128...
$ `2013__Non-Group` <dbl> 13816000, 174200, 24000, 170800, 155600, ...
$ `2013__Medicaid` <dbl> 54919100, 869700, 95000, 1346100, 600800,...
$ `2013__Medicare` <dbl> 40876300, 783000, 55200, 842000, 515200, ...
$ `2013__Other Public` <chr> "6295400", "85600", "60600", "N/A", "6760...
$ `2013__Uninsured` <dbl> 41795100, 724800, 102200, 1223000, 436800...
$ `2013__Total` <dbl> 313401200, 4763900, 702000, 6603100, 2904...
$ `2014__Employer` <dbl> 154347500, 2202800, 345300, 2835200, 1176...
$ `2014__Non-Group` <dbl> 19313000, 288900, 26800, 333500, 231700, ...
$ `2014__Medicaid` <dbl> 61650400, 891900, 130100, 1639400, 639200...
$ `2014__Medicare` <dbl> 41896500, 718400, 55300, 911100, 479400, ...
$ `2014__Other Public` <chr> "5985000", "143900", "37300", "N/A", "820...
$ `2014__Uninsured` <dbl> 32967500, 522200, 100800, 827100, 287200,...
$ `2014__Total` <dbl> 316159900, 4768000, 695700, 6657200, 2896...
$ `2015__Employer` <dbl> 155965800, 2218000, 355700, 2766500, 1293...
$ `2015__Non-Group` <dbl> 21816500, 291500, 22300, 278400, 200200, ...
$ `2015__Medicaid` <dbl> 62384500, 911400, 128100, 1711500, 641400...
$ `2015__Medicare` <dbl> 43308400, 719100, 60900, 949000, 484500, ...
$ `2015__Other Public` <chr> "6422300", "174600", "47700", "189300", "...
$ `2015__Uninsured` <dbl> 28965900, 519400, 90500, 844800, 268400, ...
$ `2015__Total` <dbl> 318868500, 4833900, 705300, 6739500, 2953...
$ `2016__Employer` <dbl> 157381500, 2263800, 324400, 3010700, 1290...
$ `2016__Non-Group` <dbl> 21884400, 262400, 20300, 377000, 252900, ...
$ `2016__Medicaid` <dbl> 62303400, 997000, 145400, 1468400, 618600...
$ `2016__Medicare` <dbl> 44550200, 761200, 68200, 1028000, 490000,...
$ `2016__Other Public` <chr> "6192200", "128800", "55600", "172500", "...
$ `2016__Uninsured` <dbl> 28051900, 420800, 96900, 833700, 225500, ...
$ `2016__Total` <dbl> 320372000, 4834100, 710800, 6890200, 2945...
\end{verbatim}
\hypertarget{read-the-state-information-using-the-datasets-r-package}{%
\subsection{\texorpdfstring{Read the State information using the
\texttt{datasets} R
package}{Read the State information using the datasets R package}}\label{read-the-state-information-using-the-datasets-r-package}}
Since our goal is to get sense of the health expenditure, including
healthcare coverage and healthcare spending, \textbf{across States}, it
would be nice add some information about each state. Namely, the state
abbreviation and state region (i.e.~north, south, etc).
For this we use the
\href{https://stat.ethz.ch/R-manual/R-devel/library/datasets/html/state.html}{state}
dataset in the \texttt{datasets} R package.
Before we begin, let's look at what states are there:
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{unique}\NormalTok{(coverage}\OperatorTok{$}\NormalTok{Location)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
[1] "United States" "Alabama" "Alaska"
[4] "Arizona" "Arkansas" "California"
[7] "Colorado" "Connecticut" "Delaware"
[10] "District of Columbia" "Florida" "Georgia"
[13] "Hawaii" "Idaho" "Illinois"
[16] "Indiana" "Iowa" "Kansas"
[19] "Kentucky" "Louisiana" "Maine"
[22] "Maryland" "Massachusetts" "Michigan"
[25] "Minnesota" "Mississippi" "Missouri"
[28] "Montana" "Nebraska" "Nevada"
[31] "New Hampshire" "New Jersey" "New Mexico"
[34] "New York" "North Carolina" "North Dakota"
[37] "Ohio" "Oklahoma" "Oregon"
[40] "Pennsylvania" "Rhode Island" "South Carolina"
[43] "South Dakota" "Tennessee" "Texas"
[46] "Utah" "Vermont" "Virginia"
[49] "Washington" "West Virginia" "Wisconsin"
[52] "Wyoming"
\end{verbatim}
We see there are more than 50 states because ``United States'' and
``District of Columbia'' are both included.
Let's look what states are inside the \texttt{state} dataset.
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{library}\NormalTok{(datasets)}
\KeywordTok{data}\NormalTok{(state)}
\KeywordTok{unique}\NormalTok{(state.name)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
[1] "Alabama" "Alaska" "Arizona" "Arkansas"
[5] "California" "Colorado" "Connecticut" "Delaware"
[9] "Florida" "Georgia" "Hawaii" "Idaho"
[13] "Illinois" "Indiana" "Iowa" "Kansas"
[17] "Kentucky" "Louisiana" "Maine" "Maryland"
[21] "Massachusetts" "Michigan" "Minnesota" "Mississippi"
[25] "Missouri" "Montana" "Nebraska" "Nevada"
[29] "New Hampshire" "New Jersey" "New Mexico" "New York"
[33] "North Carolina" "North Dakota" "Ohio" "Oklahoma"
[37] "Oregon" "Pennsylvania" "Rhode Island" "South Carolina"
[41] "South Dakota" "Tennessee" "Texas" "Utah"
[45] "Vermont" "Virginia" "Washington" "West Virginia"
[49] "Wisconsin" "Wyoming"
\end{verbatim}
Ah, ok. So let's start by dealing with DC as a special case.
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{state.abb <-}\StringTok{ }\KeywordTok{c}\NormalTok{(state.abb, }\StringTok{"DC"}\NormalTok{)}
\NormalTok{state.region <-}\StringTok{ }\KeywordTok{as.factor}\NormalTok{(}\KeywordTok{c}\NormalTok{(}\KeywordTok{as.character}\NormalTok{(state.region), }\StringTok{"South"}\NormalTok{))}
\NormalTok{state.name <-}\StringTok{ }\KeywordTok{c}\NormalTok{(state.name, }\StringTok{"District of Columbia"}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
We will deal with the ``United States'' in the next section.
\hypertarget{data-wrangling}{%
\section{Data Wrangling}\label{data-wrangling}}
\hypertarget{what-is-tidy-data}{%
\subsection{What is ``Tidy Data''?}\label{what-is-tidy-data}}
\hypertarget{glance-at-tidy-data}{%
\paragraph{Glance at ``Tidy Data''}\label{glance-at-tidy-data}}
A subset of the data analysis process can be thought about in the
following way:
\includegraphics[width=0.95\linewidth]{http://r4ds.had.co.nz/diagrams/data-science}
where each of these steps needs its own tools and software to complete.
After we import the data into R, if we are going to take advantage of
the \emph{``tidyverse''}, this means we need to \emph{transform} the
data into a form that is \emph{``tidy''}. If you recall, in \emph{tidy}
data:
\begin{itemize}
\tightlist
\item
Each variable forms a column.
\item
Each observation forms a row.
\item
Each type of observational unit forms a table.
\end{itemize}
For example, consider the following dataset:
\includegraphics{https://github.com/datasciencelabs/2016/raw/master/lectures/wrangling/pics/stocks-by-company.png}
Here:
\begin{itemize}
\tightlist
\item
each row represents one company (row names are companies)
\item
each column represent one time point
\item
the stock prices are defined for each row/column pair
\end{itemize}
Alternatively, a data set can be structured in the following way:
\begin{itemize}
\tightlist
\item
each row represents one time point (but no row names)
\item
the first column defines the time variable and the last three columns
contain the stock prices for three companies
\end{itemize}
\includegraphics{https://github.com/datasciencelabs/2016/raw/master/lectures/wrangling/pics/stocks-by-time.png}
In both cases, the data is the same, but the structure is different.
This can be \emph{frustrating} to deal with as an analyst because the
meaning of the values (rows and columns) in the two data sets are
different. Providing a standardized way of organizing values within a
data set would alleviate a major portion of this frustration.
For motivation, a \emph{tidy} version of the stock data we looked at
above looks like this: (we'll learn how the functions work in just a
moment)
\includegraphics{https://github.com/datasciencelabs/2016/raw/master/lectures/wrangling/pics/stocks-tidy.png}
In this ``tidy'' data set, we have three columns representing three
variables (time, company name and stock price). Every row represents
contains one stock price from a particular time and for a specific
company.
If we consider our \texttt{coverage} dataframe, we see it is also not in
a tidy format. Each row contains information about the coverage level by
\texttt{Location} across years and types of coverage.
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{coverage[}\DecValTok{1}\OperatorTok{:}\DecValTok{5}\NormalTok{, }\DecValTok{1}\OperatorTok{:}\DecValTok{5}\NormalTok{]}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
# A tibble: 5 x 5
Location `2013__Employer` `2013__Non-Grou~ `2013__Medicaid`
<chr> <dbl> <dbl> <dbl>
1 United ~ 155696900 13816000 54919100
2 Alabama 2126500 174200 869700
3 Alaska 364900 24000 95000
4 Arizona 2883800 170800 1346100
5 Arkansas 1128800 155600 600800
# ... with 1 more variable: `2013__Medicare` <dbl>
\end{verbatim}
Now, let's use the \texttt{tidyr} R package to transform our data into a
\emph{tidy} format.
\hypertarget{the-tidyr-r-package}{%
\subsection{\texorpdfstring{The \texttt{tidyr} R
package}{The tidyr R package}}\label{the-tidyr-r-package}}
\hypertarget{what-is-the-tidyr-r-package}{%
\subsubsection{\texorpdfstring{1. What is the \texttt{tidyr} R package
?}{1. What is the tidyr R package ?}}\label{what-is-the-tidyr-r-package}}
\href{https://cran.r-project.org/web/packages/tidyr/vignettes/tidy-data.html}{\texttt{tidyr}}
is an R package that transforms data sets to a tidy format.
This package is installed and loaded when you load the
\texttt{tidyverse} using \texttt{library(tidyverse)}. However, you can
also just load the library by itself.
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{library}\NormalTok{(tidyr)}
\end{Highlighting}
\end{Shaded}
The main functions in \texttt{tidyr} are:
\begin{longtable}[]{@{}ll@{}}
\toprule
\begin{minipage}[b]{0.03\columnwidth}\raggedright
\texttt{tidyr} functions\strut
\end{minipage} & \begin{minipage}[b]{0.91\columnwidth}\raggedright
Description\strut
\end{minipage}\tabularnewline
\midrule
\endhead
\begin{minipage}[t]{0.03\columnwidth}\raggedright
\texttt{gather()}\strut
\end{minipage} & \begin{minipage}[t]{0.91\columnwidth}\raggedright
takes multiple columns, and gathers them into key-value pairs, making
``wide'' data longer\strut
\end{minipage}\tabularnewline
\begin{minipage}[t]{0.03\columnwidth}\raggedright
\texttt{separate()}\strut
\end{minipage} & \begin{minipage}[t]{0.91\columnwidth}\raggedright
turns a single character column into multiple columns, making ``long''
data wider\strut
\end{minipage}\tabularnewline
\begin{minipage}[t]{0.03\columnwidth}\raggedright
\texttt{spread()}\strut
\end{minipage} & \begin{minipage}[t]{0.91\columnwidth}\raggedright
spread rows into multiple columns, transforming ``long'' data into
``wide'' format\strut
\end{minipage}\tabularnewline
\bottomrule
\end{longtable}
We'll explore what it means to go between a ``wide'' and ``long'' data
format using \texttt{gather()} , \texttt{separate()}, and
\texttt{spread()}.
A
\href{https://www.rstudio.com/wp-content/uploads/2015/02/data-wrangling-cheatsheet.pdf}{\texttt{tidyr}
cheatsheet} for the functions in the \texttt{tidyr} package can be found
on RStudio's website:
\hypertarget{convert-data-from-wide-format-to-long-format-using-gather}{%
\subsubsection{\texorpdfstring{2. Convert data from wide format to long
format using
\texttt{gather()}}{2. Convert data from wide format to long format using gather()}}\label{convert-data-from-wide-format-to-long-format-using-gather}}
Let's start by looking at the \texttt{gather()} help file
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{?gather}
\end{Highlighting}
\end{Shaded}
This function gathers multiple columns and collapses them into new
\emph{key-value} pairs. This transform data from \emph{wide} format into
a \emph{long} format.
\begin{itemize}
\tightlist
\item
The \texttt{key} is the name of the \emph{new} column that you are
creating which contains the values of the column headings that you are
gathering
\item
The \texttt{value} is the name of the \emph{new} column that will
contain the values themselves
\item
The third argument defines the columns to gather
\end{itemize}
For example, here we create a column titled \texttt{year\_type} and
\texttt{coverage}. We also want to keep the \texttt{Location} column as
it is because it also contains observational level data.
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{coverage <-}\StringTok{ }\KeywordTok{gather}\NormalTok{(coverage, }\StringTok{"year_type"}\NormalTok{, }\StringTok{"tot_coverage"}\NormalTok{, }\OperatorTok{-}\NormalTok{Location)}
\NormalTok{coverage}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
# A tibble: 1,456 x 3
Location year_type tot_coverage
<chr> <chr> <chr>
1 United States 2013__Employer 155696900
2 Alabama 2013__Employer 2126500
3 Alaska 2013__Employer 364900
4 Arizona 2013__Employer 2883800
5 Arkansas 2013__Employer 1128800
6 California 2013__Employer 17747300
7 Colorado 2013__Employer 2852500
8 Connecticut 2013__Employer 2030500
9 Delaware 2013__Employer 473700
10 District of Columbia 2013__Employer 324300
# ... with 1,446 more rows
\end{verbatim}
Now we see each row contains one observation. Namely, a
\texttt{Location}, a \texttt{year\_type} and \texttt{coverage}. It would
be nice to separate out the information in the \texttt{year\_type}
column into two columns. We can implement same techniques to the
healthcare spending dataset.
\hypertarget{convert-healthcare-spending-data-to-a-long-format-tidy-format}{%
\paragraph{Convert healthcare spending data to a long format (tidy
format)}\label{convert-healthcare-spending-data-to-a-long-format-tidy-format}}
Let's do the same for the \texttt{spending} data. In this case I will
use \texttt{year} and \texttt{spending} for the \texttt{key} and
\texttt{value}. We also want to keep \texttt{Location} like before.
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{spending <-}\StringTok{ }\KeywordTok{gather}\NormalTok{(spending, }\StringTok{"year"}\NormalTok{, }\StringTok{"tot_spending"}\NormalTok{, }\OperatorTok{-}\NormalTok{Location)}
\NormalTok{spending}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
# A tibble: 1,248 x 3
Location year tot_spending
<chr> <chr> <dbl>
1 United States 1991__Total Health Spending 675896
2 Alabama 1991__Total Health Spending 10393
3 Alaska 1991__Total Health Spending 1458
4 Arizona 1991__Total Health Spending 9269
5 Arkansas 1991__Total Health Spending 5632
6 California 1991__Total Health Spending 81438
7 Colorado 1991__Total Health Spending 8460
8 Connecticut 1991__Total Health Spending 10950
9 Delaware 1991__Total Health Spending 1938
10 District of Columbia 1991__Total Health Spending 2800
# ... with 1,238 more rows
\end{verbatim}
We will explore how to do that in the Data Wrangling section below. For
now let's learn more about the \texttt{tidyr} package.