-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2022-07-11_day_1_slides.html
2428 lines (1903 loc) · 91.2 KB
/
2022-07-11_day_1_slides.html
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
<!DOCTYPE html>
<html lang="" xml:lang="">
<head>
<title>Intro to Data Wrangling, Exploration, and Analysis with R</title>
<meta charset="utf-8" />
<meta name="author" content="Nina Brooks Assistant Professor, UConn School of Public Policy" />
<meta name="date" content="2022-07-11" />
<script src="2022-07-11_day_1_slides_files/header-attrs/header-attrs.js"></script>
<link href="2022-07-11_day_1_slides_files/remark-css/default.css" rel="stylesheet" />
<link href="2022-07-11_day_1_slides_files/remark-css/default-fonts.css" rel="stylesheet" />
</head>
<body>
<textarea id="source">
class: center, middle, inverse, title-slide
.title[
# Intro to Data Wrangling, Exploration, and Analysis with R
]
.subtitle[
## Summer 2022 Workshop: Day 1
]
.author[
### Nina Brooks<br> Assistant Professor, UConn School of Public Policy
]
.date[
### July 11, 2022
]
---
# Welcome
My name is [Nina Brooks](www.ninarbrooks.com). I am an Assistant Professor in the UConn School of Public Policy and an R enthusiast!
<br>
--
This short course is designed to introduce you to the R programming language and get a sense of its possibilities for your own projects.
<br>
--
By the end of this 2-day course, you will see how to do the following in R:
--
- Load variety of different data types
--
- Prepare data for analysis by creating new variables, reshaping data, & identifying duplicates and missing values
--
- Create summary tables
--
- Run regressions
--
- Create data visualizations
--
- And most importantly, where to find help
.footnote[
*I relied heavily on the materials from [Stat545](https://stat545.com/), [Tidyverse Skills](https://jhudatascience.org/tidyversecourse/wrangle-data.html), and [IPUMS PMA Data Analysis Hub](https://tech.popdata.org/pma-data-hub/) for creating this workshop
]
???
Emphasize that this is a bit of a survey course - i'll cover a lot of topics in brief, but won't go into depth in any of them. also, this is not a statistics class - i will discuss certain topics you may have learned in other courses (hypothesis testing, regression, etc), but I will not spend any time in this workshop discussing the theory behind them - only demonstrating how to do them in R
---
name: agenda
# Agenda
.pull-left[## Day 1
1. Intro to R
2. Reading in different types of Data
3. Data manipulation with the [tidyverse](https://www.tidyverse.org/)
]
--
.pull-right[## Day 2
1. Descriptive statistics & nice looking tables
2. Linear Regression & exporting nice looking tables
3. Data Visualization
]
???
Everyone should have access to today's slides, as well as all of the data and code used in the 2-day workshop.
I will also toggle between the slides and doing live demo in R
---
name: rintro
layout: true
# R and RStudio
---
--
## Did you do the pre-workshop setup?
- Download and install [R](https://cloud.r-project.org/) or update if you had a previous installation
- Download and install [RStudio](https://www.rstudio.com/) or update if you had a previous installation
- Install the packages sent in the "2022-R-Summer-Workshop-Setup.pdf"
--
## No?
- We won't have time to address R or RStudio installation issues during this workshop
- You can follow along with the slides and my shared screens of my R environment
- Reach out to me afterwards about individual issues, although I can't troubleshoot everyone's individual setup
---
## What is R?
--
R is a system for statistical computation and graphics. It consists of a language plus a run-time environment with graphics, a debugger, access to certain system functions, and the ability to run programs stored in script files.
--
R is **free** and open source, has a large group of users that provide support and develop R packages to augment the functions of base R, can be used to perform statistical analyses of all types, make data visualizations, apply machine learning algorithms, and do web scraping, as well as make slides (like these!), prepare documents, such as academic manuscripts or books, build [websites](www.ninarbrooks.com), create interactive web applications, among many other things!
--
## What is R Studio?
RStudio is an integrated development environment or IDE for using R. You need to install R first to also use RStudio. I highly recommend using RStudio instead of just R because it provides a powerful and user-friendly interface for interacting with R.
???
this is a pretty complex definition of R - the thing to take away is that it is a programming language with the ability to do statistical analysis and produce graphics (eg visualizations).
In fact, I will not even show anything in the base R environment.
---
## Add-on packages
There are many user-written packages (that are well maintained and publicly available) to support the functioning of base R. It is easy to install a package directly in the R console:
```r
install.packages("tidyverse", dependencies = TRUE)
```
--
A few comments:
- By including `dependencies = TRUE`, we are being explicit and extra-careful to install any additional packages the target package, tidyverse in the example above, needs to have around.
- The name of the package must be enclosed in quotes
- `install.packages` not `install.package` (it's plural)
- Package names are case sensitive: `"tidyverse"` is not the same as `"Tidyverse"` or `"tidyVerse"`
---
layout: false
# Further resources
Here are some links if you are interested in reading a bit further
- [How to Use RStudio](https://support.rstudio.com/hc/en-us)
- [Getting Help with R from RStudio](https://support.rstudio.com/hc/en-us/articles/200552336-Getting-Help-with-R)
- [R FAQ](https://cloud.r-project.org/)
- [R Installation and Administration](https://cloud.r-project.org/doc/manuals/r-release/R-admin.html)
---
# Objects & Data Structures
.pull-left[
R has 6 basic data types:
- character: `"a"`, `"R has 6 basic data types."`
- numeric (real or decimal): `2`, `17.5`
- integer: `2L`(the L tells R to store this as an integer)
- logical: `TRUE`, `FALSE`
- complex: `1+4i`
]
--
.pull-right[
R also has different data structures:
- atomic vector
- list
- matrix
- data frame
- factors
]
???
The data frame is going to be the primary type of data structure most of you will be working with. Data frames refer to tabulaur/rectangular/spreadsheet style data. As we'll see a little later today, when you work with the tidyverse, data frames are also stored as "tibbles" - but these operate just like data frames for all intensive purposes.
R has other data structures as well, for example, you can import different types of spatial datasets into R and also text data.
---
# R basics
All R statements where you create objects – “assignments” – have this form:
```r
objectName <- value
```
You should **always** use the `<-` operator when assigning objects in R.
--
For example:
```r
x <- 3 * 4
*x
```
```
## [1] 12
```
```r
example <- "This is a string"
*example
```
```
## [1] "This is a string"
```
The highlighted lines of code tell R you want to print out whatever is stored in the object "x" or the object "example".
---
# R Scripts
To make your code reproducible, you should always work from a well-annotated R script. These are saved with the file extension `".R"` For example, `"2022_summer_workshop.R"`.
--
It is also common to write code in R Markdown documents, which are saved with the file extension `".Rmd"`. For example, `"2022_summer_workshop.Rmd"`.
--
The big difference between an R script and an Rmd document is that Rmd documents are typically intended to weave together narrative text and code together, whereas R scripts contain only code. If you wanted to write a report based on your analysis, you could include both the analysis, writing, and output (e.g. tables, plots, regressions) in a single R Markdown document that is compiled into a clean report.
--
To make a comment in your R code (in either an R script or Rmd document), use the `#` before the text you want to comment. To comment out an entire line of code, put the `#` before the code:
```r
example <- "This is a string" # this line of code demonstrates how to assign a string object
# example2 <- "Hello World." # this entire line is commented out and will not be evaluated
```
---
# Misc important commands
To identify or change your working directory:
```r
# identify current working directory
getwd()
# change working directory
setwd("~/Users/nib21006/my_research_project") # must be contained in quotes!
```
To remove objects in your environment:
```r
rm(example) # removes the object called "example"
rm(list = ls()) # removes everything in the environment
```
Get help from within R on any command (even without an internet connection!):
```r
?getwd
help(getwd)
```
---
# Workflow
I recommend the following workflow:
- Write code in an R script or Rmd document
- Annotate it well, so your future self understands what you did and why
- Pro move: use Git or GitHub for version control (you can easily integrate this with RStudio)
- Keep an organized working directory with separate folders for raw data, clean data, output (like figures or tables), and scripts
- The precise structure will depend a bit on your needs
- Save your R script/Rmd document! But no need to save your workspace (R will ask you this when you quit). And definitely **never** save an edited or manipulated version of your raw data
- The ability to reproduce your clean data is exactly why you have your script(s)!
---
class: center, inverse, middle
# LET'S SEE SOME R!
???
In R Studio walk through:
- panels
1. Source (where your R script is)
2. console (this is where the output goes)
3. environment (what's loaded in R, files, plots, help & viewer)
4. "everything else"
- can customize the layout (show this) & change colors
- R script - header, comments
- demonstrate running code up through reading in data
---
name: read_data
layout: true
# Importing Data into R
---
Data are stored in all sorts of different file formats and structures. We’ll discuss each of these common formats and discuss how to get them into R so you can start working with them!
--
## Excel files
Microsoft Excel files, which typically have the file extension .xls or .xlsx, store information in a workbook. Excel files can only be viewed in specific pieces of software (like Microsoft Excel), and thus are generally less flexible than many other formats of storing data.
Additionally, Excel has certain defaults that make working with Excel data difficult outside of Excel. For example, Excel has a habit of aggressively changing data types. For example if you type 1/2, to mean 0.5, Excel assumes it is a date and converts that information to January 2nd.
.footnote[
*Special thanks to [Tidyverse Skills](https://jhudatascience.org/tidyversecourse/wrangle-data.html) for the content in this section.
]
---
Reading Excel spreadsheets into R is made possible thanks to the `readxl` package. You’ll need to install and load the package in before use.
```r
# install.packages("readxl")
library(readxl)
```
--
You will use the function `read_excel()` to read an Excel file into your R Environment. The only required argument of this function is the path to the Excel file on your computer. In the following example, `read_excel()` would look for the file “filename.xlsx” in your **current working directory.** If the file were located somewhere else on your computer, you would have to provide the path to that file
```r
# read Excel file into R
excel_df <- read_excel("filename.xlsx")
```
---
## Google Sheets files
Many of you probably work in Google Sheets instead of Excel. While you could download data stored in Google Sheets as an Excel file and then import it into R using the `readxl` package, there's a package that allows you to read in a Google Sheets file directly from the Internet, where it lives: `googlesheets4`!
--
Note that if the data hosted on Google Sheets changes, every time the file is read into R, the most updated version of the file will be utilized. This can be very helpful if you’re collecting data over time; however, it could lead to unexpected changes in results if you’re not aware that the data in the Google Sheet is changing.
```r
# install.packages("googlesheets4")
# load package
library(googlesheets4)
```
--
The `googlesheets4` package allows R users to take advantage of the Google Sheets Application Programming Interface (API). Very generally, APIs allow different applications to communicate with one another. In this case, Google has released an API that allows other software to communicate with Google Drive and retrieve data and information directly from Google Sheets.
---
Every time you start a new session, you need to authenticate the use of the `googlesheets4` package with your Google account.
```r
gs4_auth() # run this to open the Google API authenticator
```
You can use `googlesheets4` to search through the various Google Sheets in your account using `gs4_find()`. Then, you can use the `read_sheets()` function by typing in the id listed for your Google Sheet of interest when using `gs4_find()`.
```r
gs4_find()
# read Google Sheet into R with id
read_sheet("2cdw-678dSPLfdID__LIt8eEFZPasdebgIGwHk") # note this is a fake id
```
---
You can also navigate to your own sheets or to other people’s sheets using a URL.
```r
# read Google Sheet into R with URL
googlesheet_df <- read_sheet("https://docs.google.com/spreadsheets/d/1FN7VVKzJJyifZFY5POdz_LalGTBYaC4SLB-X9vyDnbY/")
googlesheet_df
```
```
## # A tibble: 5 × 7
## name hrs_working hrs_sleeping hrs_fun hrs_eating hrs_socializing hrs_other
## <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 Damon 9 7 1 1 2 4
## 2 Lilly 7 8 2 1 1 5
## 3 Will 8 8 0 2 2 4
## 4 Aisha 8 6 2 1 4 3
## 5 Hassan 6 9 3 2 2 2
```
---
## CSV files
Like Excel Spreadsheets and Google Sheets, Comma-separated values (CSV) files allow us to store tabular data. Note that CSV files have a .csv extension at the end. CSVs are plain-text files. This means that there are no workbooks or metadata making it difficult to open these files.
--
One of the advantages of CSV files is their simplicity. CSVs are flexible files and are thus the preferred storage method for tabular data for many researchers.
--
You can read .csv files directly into R using a "base" R command: `read.csv()`. However, we'll use the `tidyverse` version in this workshop, which is `read_csv()` from the `readr` package, which is loaded when you load the `tidyverse`.
```r
# install.packages("tidyverse")
# load package
library(tidyverse)
```
---
To read in a .csv file using the `readr::read_csv()` command is simple. Without any additional steps, it automatically knows that the first row of the file contains the variable names and figures out the "type" of most variables (although not the `day` variable - we'll talk about dates later!)
```r
# read CSV into R
csv_df <- read_csv("./data/weather_data.csv")
# look at the object
# you can you head() or just print the df, if it's a tibble
# it will only print out the first 10 rows anyway!
head(csv_df)
```
```
## # A tibble: 6 × 8
## day season month ws wd dewpoint temp rain
## <chr> <chr> <chr> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 11/28/18 Kilns On Nov 1.20 354. 287. 294. 0.0000014
## 2 11/29/18 Kilns On Nov 1.01 344. 287. 294. 0.00000104
## 3 11/30/18 Kilns On Nov 1.15 314. 287. 294. 0.00000144
## 4 12/1/18 Kilns On Dec 1.29 341. 287. 294. 0.000000108
## 5 12/2/18 Kilns On Dec 1.33 326. 287. 294. 0
## 6 12/3/18 Kilns On Dec 1.75 348. 287. 294. 0
```
---
If you had a few extra rows of information that you didn't want to import as part of your data frame, you can easily skip those:
```r
# read CSV into R
csv_df <- read_csv("./data/weather_data.csv", skip = 3) # skips the first 3 rows
# look at the object
csv_df # see how more rows are printed out when we didn't use the head() command?
```
```
## # A tibble: 250 × 8
## `11/30/18` `Kilns On` Nov `1.15185662` `314.1624506` `286.879566`
## <chr> <chr> <chr> <dbl> <dbl> <dbl>
## 1 12/1/18 Kilns On Dec 1.29 341. 287.
## 2 12/2/18 Kilns On Dec 1.33 326. 287.
## 3 12/3/18 Kilns On Dec 1.75 348. 287.
## 4 12/4/18 Kilns On Dec 1.95 319. 288.
## 5 12/5/18 Kilns On Dec 1.98 318. 288.
## 6 12/6/18 Kilns On Dec 1.84 307. 287.
## 7 12/7/18 Kilns On Dec 1.76 322. 287.
## 8 12/8/18 Kilns On Dec 2.25 325. 286.
## 9 12/9/18 Kilns On Dec 1.79 332. 287.
## 10 12/10/18 Kilns On Dec 1.59 349. 286.
## # … with 240 more rows, and 2 more variables: `293.8420586` <dbl>,
## # `1.44E-06` <dbl>
```
---
## Text (.txt) files
Sometimes, tab-separated files are saved with the .txt file extension. TXT files can store tabular data, but they can also store simple text. In these cases, you’ll want to use the more generic `read_delim()` function from readr.
```r
# read a TXT file into R
txt_df <- read_delim("./data/HAP0006.txt", delim = ",") # specify the delimiter
# look at the object
head(txt_df)
```
```
## # A tibble: 6 × 12
## household device Time specCO figaroCO2 plantower_2_5_v… plantower_10_va…
## <chr> <chr> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 Icddrb test HAP0006 1.54e9 1671 2711 36 39
## 2 Icddrb test HAP0006 1.54e9 1671 2722 37 46
## 3 Icddrb test HAP0006 1.54e9 1671 2688 37 39
## 4 Icddrb test HAP0006 1.54e9 1671 2765 37 43
## 5 Icddrb test HAP0006 1.54e9 1671 2689 48 59
## 6 Icddrb test HAP0006 1.54e9 1671 2646 41 49
## # … with 5 more variables: bme_temp_C <dbl>, bme_humidity <dbl>,
## # fuel_v_cell <dbl>, fuel_percent <dbl>, loggedAt <dttm>
```
???
view the hap.txt file (within R) just to show what a .txt file looks like
---
## Stata .dta files
You can import Stata .dta files directly into R using the `haven` package. This package also allows you to import SAS or SPSS files. The command within the package you'll use is `read_dta()` (notice the pattern?):
```r
# install.packages("haven")
library(haven)
dta_df <- read_dta("./data/lead_mortality.dta")
# look at the object
head(dta_df)
```
```
## # A tibble: 6 × 15
## year city state age hardness ph infrate typhoid_rate np_tub_rate
## <dbl> <chr> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 1900 Alameda CA 29.0 97 7.60 0.110 0.0244 0.0305
## 2 1900 Albany NY 30.3 43 7.30 0.299 0.0414 0.0138
## 3 1900 Allegheny PA 27.1 111 7.30 0.447 0.0940 0.0277
## 4 1900 Allentown PA 27.8 176 7.70 0.384 0.0282 0.00565
## 5 1900 Altoona PA 27.0 111 7.30 0.468 0.0437 0.00771
## 6 1900 Amsterdam NY 28.6 43 7.30 0.306 0.0144 0.0191
## # … with 6 more variables: mom_rate <dbl>, population <dbl>,
## # precipitation <dbl>, temperature <dbl>, lead <dbl>, foreign_share <dbl>
```
---
## API Data
We already saw how to use an API to access data stored in Google Sheets. APIs can be used to access many other sources of data as well - and many people have written special packages that allow users of common sources of data to authenticate their credentials and then easily import data into R. I won't go through how to use them all - but will list a few common ones:
- [tidycensus](https://walker-data.com/tidycensus/) is an R package that allows users to interface with a select number of the US Census Bureau’s data APIs and return tidyverse-ready data frames.
- [rdhs](https://cran.r-project.org/web/packages/rdhs/vignettes/client.html) allows users to access, search, download, and load USAID's Demographic and Health Survey data.
- [qualtRics](https://cran.r-project.org/web/packages/qualtRics/vignettes/qualtRics.html) implements the retrieval of survey data using the Qualtrics API and aims to reduce the pre-processing steps needed in analyzing such surveys.
---
layout:true
# Exporting Data
---
R has several native formats for writing R objects. These are both very efficient in terms of space as well.
- .rds files: can store a single R object, such as a data frame
- .Rdata or .Rda files: can store multiple objects (think of it like a list)
--
Rds files:
```r
# saves the object "dta_df" as an Rds file
saveRDS(dta_df, file = "./output/example.rds")
# load an Rds fike
rds_df <- readRDS("./output/example.rds")
```
--
Rdata files:
```r
# saves all the dataframes as a single Rdata file
save(excel_df, googlesheet_df, csv_df, txt_df, dta_df,
file = "./output/all_dfs.Rdata")
# loads the Rdata file
load("./output/all_dfs.Rdata")
```
???
Note that for rds we use "saveRDS" and "readRDS" and the file extension is .rds, but for Rdata, we just use save and load and the file extension is .Rdata - these differences matter!
---
You can also export data in many formats using the `write` versions of these commands. This can be useful if you're collaborating with people who use different programs.
You need to specify the object name and the file path with the correct file extension, for the file it will be written to.
```r
# Write to csv
write_csv(dta_df, file = "./output/example.csv")
# Write to stata
write_dta(csv_df, file = "./output/example.dta")
```
---
layout:false
class: middle, center, inverse
# Questions?
---
layout:true
# Data Wrangling
---
Before we get into "data wrangling" in the Tidyverse, we have to understand what [tidy data](https://www.jstatsoft.org/article/view/v059i10) are.
--
## Principles of Tidy Data
.footnote[*The tidyverse has a very strong opinion about what "tidy" data is. I agree with most of the principles, but think there are plenty of cases in which people need to work with "untidy" data by the tidyverse definitions.]
1. Each variable should be in one column.
--
2. Each observation of that variable should be in a different row.
--
3. There should be one table for each “type” of data.
--
4. If you have multiple tables, they should include a column in each spreadsheet (with the same column label!) that allows them to be joined or merged.
???
An example of different types of data could be demographic information about patients, which would be stored in one data frame, and measurements collected from those patients at the doctor (such as height, weight, and BP) in another tidy data frame. Clearly, depending on your research question, you may need to merge these into a single data frame to run a regression of BP on patient demographics.
---
layout:false
# Examples of "untidy" data
![untidyy](./figs/untidy.png)
???
What makes these "untidy"?
---
# Example of tidy data
![tidy](./figs/tidy-1.png)
---
# Tidying Process aka Data Wrangling
![untidy_to_tidy](./figs/untidy_to_tidy.png)
---
# The pipe operator <img src="./figs/pipe.png" alt="pipe" width="60"/>
Pipes, or `%>%` are a `tidyverse` tool (officially contained in the `magrittr` package) for chaining multiple operations on the same data frame together. They can greatly simplify your code and make your operations more intuitive. I'll introduce them now, and soon you'll see how useful they can be! Note that if you're not using pipes, you'll have to specify a data frame directly as an argument to any commands you use.
--
```r
# head(dta_df) # this is how you specify the data argument
dta_df %>%
head()
```
```
## # A tibble: 6 × 15
## year city state age hardness ph infrate typhoid_rate np_tub_rate
## <dbl> <chr> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 1900 Alameda CA 29.0 97 7.60 0.110 0.0244 0.0305
## 2 1900 Albany NY 30.3 43 7.30 0.299 0.0414 0.0138
## 3 1900 Allegheny PA 27.1 111 7.30 0.447 0.0940 0.0277
## 4 1900 Allentown PA 27.8 176 7.70 0.384 0.0282 0.00565
## 5 1900 Altoona PA 27.0 111 7.30 0.468 0.0437 0.00771
## 6 1900 Amsterdam NY 28.6 43 7.30 0.306 0.0144 0.0191
## # … with 6 more variables: mom_rate <dbl>, population <dbl>,
## # precipitation <dbl>, temperature <dbl>, lead <dbl>, foreign_share <dbl>
```
???
When you use the pipe, you start with the name of the df and then chain commands onto that dataframe from the pipe.
---
layout:true
# Basic data frame operations
---
To see how these work, let's use the World Bank [World Development Indicators Data](https://databank.worldbank.org/source/world-development-indicators), which we read into R earlier using `read_excel()`.
```r
wdi <- read_excel("./data/Data_Extract_From_World_Development_Indicators.xlsx",
n_max = max(which(wdi$`Country Name` == "Zimbabwe")))
head(wdi)
```
```
## # A tibble: 6 × 16
## `Country Name` `Country Code` `Series Name` `Series Code` `2010 [YR2010]`
## <chr> <chr> <chr> <chr> <chr>
## 1 Afghanistan AFG Access to electri… EG.ELC.ACCS.… 42.70000076293…
## 2 Afghanistan AFG Educational attai… SE.SEC.CUAT.… ..
## 3 Afghanistan AFG Educational attai… SE.SEC.CUAT.… ..
## 4 Afghanistan AFG Poverty gap at $1… SI.POV.GAPS ..
## 5 Afghanistan AFG Incidence of mala… SH.MLR.INCD.… 12.98047343667…
## 6 Afghanistan AFG Individuals using… IT.NET.USER.… 4
## # … with 11 more variables: `2011 [YR2011]` <chr>, `2012 [YR2012]` <chr>,
## # `2013 [YR2013]` <chr>, `2014 [YR2014]` <chr>, `2015 [YR2015]` <chr>,
## # `2016 [YR2016]` <chr>, `2017 [YR2017]` <chr>, `2018 [YR2018]` <chr>,
## # `2019 [YR2019]` <chr>, `2020 [YR2020]` <chr>, `2021 [YR2021]` <chr>
```
???
Talk through what the WDI data contains. All countries, different series, 2010-2021. Explain how it's wide & long - with different years stored as variables and different variables stored in rows -- very untidy data!
---
The opposite of `head` is `tail`:
```r
tail(wdi)
```
```
## # A tibble: 6 × 16
## `Country Name` `Country Code` `Series Name` `Series Code` `2010 [YR2010]`
## <chr> <chr> <chr> <chr> <chr>
## 1 Zimbabwe ZWE Individuals using… IT.NET.USER.… 6.4
## 2 Zimbabwe ZWE Labor force parti… SL.TLF.CACT.… ..
## 3 Zimbabwe ZWE Labor force parti… SL.TLF.CACT.… ..
## 4 Zimbabwe ZWE Prevalence of und… SN.ITK.DEFC.… ..
## 5 Zimbabwe ZWE Military expendit… MS.MIL.XPND.… 0.816251453246…
## 6 Zimbabwe ZWE GDP per capita (c… NY.GDP.PCAP.… 1110.447012348…
## # … with 11 more variables: `2011 [YR2011]` <chr>, `2012 [YR2012]` <chr>,
## # `2013 [YR2013]` <chr>, `2014 [YR2014]` <chr>, `2015 [YR2015]` <chr>,
## # `2016 [YR2016]` <chr>, `2017 [YR2017]` <chr>, `2018 [YR2018]` <chr>,
## # `2019 [YR2019]` <chr>, `2020 [YR2020]` <chr>, `2021 [YR2021]` <chr>
```
---
`names()` or `ls()` or `colnames()` will all give you the variable names of a dataframe:
--
```r
names(wdi)
```
```
## [1] "Country Name" "Country Code" "Series Name" "Series Code"
## [5] "2010 [YR2010]" "2011 [YR2011]" "2012 [YR2012]" "2013 [YR2013]"
## [9] "2014 [YR2014]" "2015 [YR2015]" "2016 [YR2016]" "2017 [YR2017]"
## [13] "2018 [YR2018]" "2019 [YR2019]" "2020 [YR2020]" "2021 [YR2021]"
```
```r
ls(wdi) # not that ls prints them in alphabetical order, while the other 2 print them in the order they appear in the df
```
```
## [1] "2010 [YR2010]" "2011 [YR2011]" "2012 [YR2012]" "2013 [YR2013]"
## [5] "2014 [YR2014]" "2015 [YR2015]" "2016 [YR2016]" "2017 [YR2017]"
## [9] "2018 [YR2018]" "2019 [YR2019]" "2020 [YR2020]" "2021 [YR2021]"
## [13] "Country Code" "Country Name" "Series Code" "Series Name"
```
```r
colnames(wdi)
```
```
## [1] "Country Name" "Country Code" "Series Name" "Series Code"
## [5] "2010 [YR2010]" "2011 [YR2011]" "2012 [YR2012]" "2013 [YR2013]"
## [9] "2014 [YR2014]" "2015 [YR2015]" "2016 [YR2016]" "2017 [YR2017]"
## [13] "2018 [YR2018]" "2019 [YR2019]" "2020 [YR2020]" "2021 [YR2021]"
```
---
More ways to query basic info on a data frame:
```r
ncol(wdi) # number of columns
```
```
## [1] 16
```
```r
nrow(wdi) # number of rows
```
```
## [1] 2387
```
```r
length(wdi) # length when applied to a df also returns # of columns
```
```
## [1] 16
```
```r
dim(wdi) # dimensions of the df: rows by columns
```
```
## [1] 2387 16
```
---
You can get an overview of what's in the data frame using `summary()`:
```r
summary(wdi)
```
```
## Country Name Country Code Series Name Series Code
## Length:2387 Length:2387 Length:2387 Length:2387
## Class :character Class :character Class :character Class :character
## Mode :character Mode :character Mode :character Mode :character
## 2010 [YR2010] 2011 [YR2011] 2012 [YR2012] 2013 [YR2013]
## Length:2387 Length:2387 Length:2387 Length:2387
## Class :character Class :character Class :character Class :character
## Mode :character Mode :character Mode :character Mode :character
## 2014 [YR2014] 2015 [YR2015] 2016 [YR2016] 2017 [YR2017]
## Length:2387 Length:2387 Length:2387 Length:2387
## Class :character Class :character Class :character Class :character
## Mode :character Mode :character Mode :character Mode :character
## 2018 [YR2018] 2019 [YR2019] 2020 [YR2020] 2021 [YR2021]
## Length:2387 Length:2387 Length:2387 Length:2387
## Class :character Class :character Class :character Class :character
## Mode :character Mode :character Mode :character Mode :character
```
???
Looks like we have some work to do on this data frame! Everything is currently stored as a character.
---
Another way to see what's in a data frame (and other objects) is with the `str()` command:
```r
str(wdi)
```
```
## tibble [2,387 × 16] (S3: tbl_df/tbl/data.frame)
## $ Country Name : chr [1:2387] "Afghanistan" "Afghanistan" "Afghanistan" "Afghanistan" ...
## $ Country Code : chr [1:2387] "AFG" "AFG" "AFG" "AFG" ...
## $ Series Name : chr [1:2387] "Access to electricity (% of population)" "Educational attainment, at least completed lower secondary, population 25+, female (%) (cumulative)" "Educational attainment, at least completed lower secondary, population 25+, male (%) (cumulative)" "Poverty gap at $1.90 a day (2011 PPP) (%)" ...
## $ Series Code : chr [1:2387] "EG.ELC.ACCS.ZS" "SE.SEC.CUAT.LO.FE.ZS" "SE.SEC.CUAT.LO.MA.ZS" "SI.POV.GAPS" ...
## $ 2010 [YR2010]: chr [1:2387] "42.700000762939503" ".." ".." ".." ...
## $ 2011 [YR2011]: chr [1:2387] "43.222019195556598" ".." ".." ".." ...
## $ 2012 [YR2012]: chr [1:2387] "69.099998474121094" ".." ".." ".." ...
## $ 2013 [YR2013]: chr [1:2387] "68.2906494140625" ".." ".." ".." ...
## $ 2014 [YR2014]: chr [1:2387] "89.5" ".." ".." ".." ...
## $ 2015 [YR2015]: chr [1:2387] "71.5" ".." ".." ".." ...
## $ 2016 [YR2016]: chr [1:2387] "97.699996948242202" ".." ".." ".." ...
## $ 2017 [YR2017]: chr [1:2387] "97.699996948242202" ".." ".." ".." ...
## $ 2018 [YR2018]: chr [1:2387] "96.616134643554702" ".." ".." ".." ...
## $ 2019 [YR2019]: chr [1:2387] "97.699996948242202" ".." ".." ".." ...
## $ 2020 [YR2020]: chr [1:2387] "97.699996948242202" ".." ".." ".." ...
## $ 2021 [YR2021]: chr [1:2387] ".." "6.39573001861572" "14.865710258483899" ".." ...
```
---
To specify a single variable from a data frame, use the dollar sign `$` operator:
```r
head(wdi$`Country Name`) # note that variable names shouldn't have spaces in them; this is a "bad" variable name
```
```
## [1] "Afghanistan" "Afghanistan" "Afghanistan" "Afghanistan" "Afghanistan"
## [6] "Afghanistan"
```
```r
head(wdi$`Series Name`) # that's why they're enclosed in `back ticks`
```
```
## [1] "Access to electricity (% of population)"
## [2] "Educational attainment, at least completed lower secondary, population 25+, female (%) (cumulative)"
## [3] "Educational attainment, at least completed lower secondary, population 25+, male (%) (cumulative)"
## [4] "Poverty gap at $1.90 a day (2011 PPP) (%)"
## [5] "Incidence of malaria (per 1,000 population at risk)"
## [6] "Individuals using the Internet (% of population)"
```
---
## Recap
- You'll mostly be working with data frames and their cousin, the tibble
- Use the `tidyverse`!!! This will provide a special type of data frame called a “tibble” that has nice default printing behavior, among other benefits.
- When in doubt, `str()` something or print something.
- Always understand the basic extent of your data frames: number of rows and columns.
- Understand what variables are in your data.
- Refer to variables by name, e.g., wdi$country_name, not by column number. Your code will be more robust and readable.
---
layout:false
# Data Cleaning Packages
[`dplyr`](https://dplyr.tidyverse.org/) is the workhorse package for data cleaning in the `tidyverse`. We'll also make a lot of use [`tidyr`](https://tidyr.tidyverse.org/) and [`janitor`](https://cran.r-project.org/web/packages/janitor/vignettes/janitor.html), which is not part of the `tidyverse`.
If you've never installed these before you'll need to install them first before loading using `install.package("janitor")`, for example `dplyr` and `tidyr` are core `tidyverse` packages and will be installed automatically when you run `install.package("tidyverse")`.
Then you need to load them:
```r
library(janitor)
library(tidyverse) # loads all of the core tidyverse packages
```
---
# Cleaning up variable names
`janitor` provides useful tools for cleaning messy data, such as:
- `clean_names()` - cleans the variable names of a data frame
- `tabyl()` - provides cross-tabs get of variables (although I like the `tabulator` pacakge for this)
- `get_dupes()` - identify duplicate observations
In R, variable name must start with letter and can contain numbers, letters, underscores ('_') and periods ('.'). Special characters and spaces are not allowed. Tibbles will allow variable names that are not allowed in base R, but it can complicate things to have these. So let's fix this WDI data.
```r
# these are equivalent -- but the first uses the pipe (%>%) syntax
wdi_clean <- wdi %>%
clean_names()
wdi_clean <- clean_names(wdi)
```
???
You have to assign your new data frame to an object to save this version with clean names.If you use the same name, it will override that object with the new version.
---
# Cleaning up variable names
Let's see what the variable names look like now:
```r
head(wdi_clean)
```
```
## # A tibble: 6 × 16
## country_name country_code series_name series_code x2010_yr2010 x2011_yr2011
## <chr> <chr> <chr> <chr> <chr> <chr>
## 1 Afghanistan AFG Access to ele… EG.ELC.ACC… 42.70000076… 43.22201919…
## 2 Afghanistan AFG Educational a… SE.SEC.CUA… .. ..
## 3 Afghanistan AFG Educational a… SE.SEC.CUA… .. ..
## 4 Afghanistan AFG Poverty gap a… SI.POV.GAPS .. ..
## 5 Afghanistan AFG Incidence of … SH.MLR.INC… 12.98047343… 15.60724125…
## 6 Afghanistan AFG Individuals u… IT.NET.USE… 4 5
## # … with 10 more variables: x2012_yr2012 <chr>, x2013_yr2013 <chr>,
## # x2014_yr2014 <chr>, x2015_yr2015 <chr>, x2016_yr2016 <chr>,
## # x2017_yr2017 <chr>, x2018_yr2018 <chr>, x2019_yr2019 <chr>,
## # x2020_yr2020 <chr>, x2021_yr2021 <chr>
```
???
The default makes variable names lower case and puts an underscore where spaces used to be. You can change these defaults by specifying other available patterns - look up the help file to see what's there. Also notice how the variables that were all numeric now have an x in front of them?
---
# dplyr <img src="./figs/dplyr.png" alt="dplyr" width="60"/>
Below is a list of the main functions/commands available within `dplyr`. We won't cover all of them in this workshop. I highly recommend reviewing the documentation for [`dplyr`](https://dplyr.tidyverse.org/), which has extensive explanations and examples. The nice thing about `dplyr` functions is they're all very literal -- they do what they say:
- `mutate()` - create a new column or modify an existing column
- `glimpse()` - get an overview of what’s included in dataset (simialr to `str()`)
- `filter()` - filter rows
- `select()` - select, rename, and reorder columns
- `rename()` - rename columns
- `arrange()` - reorder rows
- `group_by()` - group variables
- `summarize()` - summarize information within a dataset
- `left_join()` - combine data across data frame (other types of joins ar also available)
- `tally()` - get overall sum of values of specified column(s) or the number of rows of tibble
- `count()` - get counts of unique values of specified column(s) (shortcut of group_by() and tally())
- `add_count()` - add values of count() as a new column
- `add_tally()` - add value(s) of tally() as a new column
---
layout: true
# Mutate
---
A lot of the data cleaning work you'll do is within the `mutate` function. For example, let's convert the country name variable into a factor and then convert these numeric variables that are being stored as strings into actual numbers.
Factors are used for storing categorical variables and have a lot of useful properties for plotting as we'll see later. Factors are comprised of two components: the actual values of the data and the possible levels within the factor. In general, the levels are friendly human-readable character strings, like “male/female” and “control/treated”. But never ever ever forget that, under the hood, R is really storing integer codes 1, 2, 3, etc.
```r
wdi <- wdi %>% # notice how i'm chaining the original wdi df to the clean_names
clean_names() %>% # which is chained to the mutate
mutate(