-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathanalysis_tidyverse.html
1376 lines (1001 loc) · 45.6 KB
/
analysis_tidyverse.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>analysis_tidyverse.knit</title>
<meta charset="utf-8" />
<script src="libs/header-attrs/header-attrs.js"></script>
<link href="libs/panelset/panelset.css" rel="stylesheet" />
<script src="libs/panelset/panelset.js"></script>
<script src="libs/xaringanExtra-webcam/webcam.js"></script>
<script id="xaringanExtra-webcam-options" type="application/json">{"width":"200","height":"200","margin":"1em"}</script>
<script src="libs/clipboard/clipboard.min.js"></script>
<link href="libs/xaringanExtra-clipboard/xaringanExtra-clipboard.css" rel="stylesheet" />
<script src="libs/xaringanExtra-clipboard/xaringanExtra-clipboard.js"></script>
<script>window.xaringanExtraClipboard(null, {"button":"Copy Code","success":"Copied!","error":"Press Ctrl+C to Copy"})</script>
<script>window.xaringanExtraClipboard(null, {"button":"Copy Code","success":"<i class=\"fa fa-check\" style=\"color: #90BE6D\"><\/i>","error":"<i class=\"fa fa-times-circle\" style=\"color: #F94144\"><\/i>"})</script>
<link href="libs/font-awesome/css/all.min.css" rel="stylesheet" />
<link href="libs/font-awesome/css/v4-shims.min.css" rel="stylesheet" />
<link rel="stylesheet" href="libs/remark-css/default.css" type="text/css" />
<link rel="stylesheet" href="libs/remark-css/metropolis.css" type="text/css" />
<link rel="stylesheet" href="libs/remark-css/metropolis-fonts.css" type="text/css" />
<link rel="stylesheet" href="libs/remark-css/custom.css" type="text/css" />
</head>
<body>
<textarea id="source">
class: cover-slide clear
<img src="img/intro-slide.png" width="95%" />
---
class: title-slide, clear
# Data Analyis with Tidyverse
### DIME Analytics
### Mer Reyes Retana
### December 7th, 2023
&nbsp;
You can find this presentation and all the materials I will use for the training in [this repository](https://github.com/dime-worldbank/data_analysis_tidyverse)
<style type="text/css">
@media print {
.has-continuation {
display: block !important;
}
}
.remark-slide-content {
font-size: 23px;
}
</style>
---
# Table of contents
1. [Introduction](#introduction)
1. [Tidy Workflow](#tidy-workflow)
1. [Tidy Verbs](#tidy-verbs)
1. [Data Visualization](#data-visualization)
1. [Conclusion and References](#conclusions)
---
class: section-slide
name: introduction
# **Introduction**
<html><div style='float:left'></div><hr color='#D38C28' size=1px width=1100px></html>
---
# Motivation
## The Critical Role of Data Preparation
**Data Science and Economics:**
- Significant time invested in data preparation
- Survey results indicate over 50% of time spent in cleaning and getting data ready
## The Challenge
- Data preparation is often challenging and time-consuming
- A crucial step in achieving accurate and reliable analysis
## Solution: Tidyverse in R
- `tidyverse`: A collection of R packages designed for data science
- Enhances efficiency and bearability in data preparation
---
# Motivation
## Who Should Attend?
- This session is open to **anyone who knows R** and is looking to **improve the style and efficiency of their code**.
--
## Requirements
- **Access to Materials**: Clone or download [this repository](https://github.com/dime-worldbank/data_analysis_tidyverse) to access the presentation materials.
- **No need to code along live**. Just sit back, and absorb the concepts.
- **After the session** you can work through the example (example/analysis_tidyverse_examples.R) at your own pace, enhancing your understanding of the Tidyverse.
---
# What is the Tidyverse?
- **The best way to use R** is by using the multiple packages it offers.
- **One such set of packages** that we are focusing on is the `tidyverse`.
<img src="img/tidyverse.jpg" width="600px" style="display: block; margin: auto;" />
- A cohesive series of R packages
- Designed with a common philosophy
- Streamlines data import, tidying, transformation, visualization, and modeling
---
class: section-slide
name: tidy-workflow
# **Tidy Workflow**
<html><div style='float:left'></div><hr color='#D38C28' size=1px width=1100px></html>
---
# Prepare your Workspace
- Install the `tidyverse` packages:
```r
install.packages("tidyverse")
install.packages("dslabs")
```
- Download/Clone [this repository](https://github.com/dime-worldbank/data_analysis_tidyverse) in your computer.
- Ready to dive in.
<img src="img/tidyverse_env.png" width="400px" style="display: block; margin: auto;" />
---
# Prepare your Workspace
**Script Set-up**
- We start by adding the libraries we will use in the project.
```r
library(tidyr) # Data tidying
library(dplyr) # Data manipulation
library(ggplot2) # Data visualization
library(dslabs) # Contains the data we will use in this presentation.
```
- Read the data
```r
data(polls_us_election_2016, package = "dslabs") # load data from package
polls_us_election_2016 <- as_tibble(polls_us_election_2016) # convert to a tibble
```
---
# Data: 2016 US election polls from the `dslabs` package
* This dataset contains __real__ data on polls made during the 2016 US Presidential elections and compiled by [fivethirtyeight](fivethirtyeight.com)
```r
library(dslabs)
library(tidyverse)
data(polls_us_election_2016, package = "dslabs") # load data from package
polls_us_election_2016 <- as_tibble(polls_us_election_2016) # convert to a tibble
head(polls_us_election_2016) # show first 6 lines of first 6 variables
```
```
## # A tibble: 6 × 15
## state startdate enddate pollster grade samplesize population
## <fct> <date> <date> <fct> <fct> <int> <chr>
## 1 U.S. 2016-11-03 2016-11-06 ABC News/Washington P… A+ 2220 lv
## 2 U.S. 2016-11-01 2016-11-07 Google Consumer Surve… B 26574 lv
## 3 U.S. 2016-11-02 2016-11-06 Ipsos A- 2195 lv
## 4 U.S. 2016-11-04 2016-11-07 YouGov B 3677 lv
## 5 U.S. 2016-11-03 2016-11-06 Gravis Marketing B- 16639 rv
## 6 U.S. 2016-11-03 2016-11-06 Fox News/Anderson Rob… A 1295 lv
## # ℹ 8 more variables: rawpoll_clinton <dbl>, rawpoll_trump <dbl>,
## # rawpoll_johnson <dbl>, rawpoll_mcmullin <dbl>, adjpoll_clinton <dbl>,
## # adjpoll_trump <dbl>, adjpoll_johnson <dbl>, adjpoll_mcmullin <dbl>
```
---
# Data: 2016 US election polls from the `dslabs` package
What variables does this dataset contain?
```r
str(polls_us_election_2016) # Displays structures of R objects
```
```
## tibble [4,208 × 15] (S3: tbl_df/tbl/data.frame)
## $ state : Factor w/ 57 levels "Alabama","Alaska",..: 50 50 50 50 50 50 50 50 37 50 ...
## $ startdate : Date[1:4208], format: "2016-11-03" "2016-11-01" ...
## $ enddate : Date[1:4208], format: "2016-11-06" "2016-11-07" ...
## $ pollster : Factor w/ 196 levels "ABC News/Washington Post",..: 1 63 81 194 65 55 18 113 195 76 ...
## $ grade : Factor w/ 10 levels "D","C-","C","C+",..: 10 6 8 6 5 9 8 8 NA 8 ...
## $ samplesize : int [1:4208] 2220 26574 2195 3677 16639 1295 1426 1282 8439 1107 ...
## $ population : chr [1:4208] "lv" "lv" "lv" "lv" ...
## $ rawpoll_clinton : num [1:4208] 47 38 42 45 47 ...
## $ rawpoll_trump : num [1:4208] 43 35.7 39 41 43 ...
## $ rawpoll_johnson : num [1:4208] 4 5.46 6 5 3 3 5 6 6 7.1 ...
## $ rawpoll_mcmullin: num [1:4208] NA NA NA NA NA NA NA NA NA NA ...
## $ adjpoll_clinton : num [1:4208] 45.2 43.3 42 45.7 46.8 ...
## $ adjpoll_trump : num [1:4208] 41.7 41.2 38.8 40.9 42.3 ...
## $ adjpoll_johnson : num [1:4208] 4.63 5.18 6.84 6.07 3.73 ...
## $ adjpoll_mcmullin: num [1:4208] NA NA NA NA NA NA NA NA NA NA ...
```
---
# The pipe operator
- Reading and understanding multiple operations can be difficult.
- Parameters are typically assigned after the function name using `()`.
```r
summarise(
group_by(
filter(polls_us_election_2016, !is.na(samplesize)),
pollster,
state
),
n = n()
)
```
- This approach can get complex really easy creating unreadable code.
---
# The pipe operator
- The pipe operator (**|>** or **%>%**) can help with this.
- The pipe is a tool to chain commands more clearly.
- With the pipe, code reads from left to right, top to bottom, which is more intuitive.
|> or %>% can be read as "then" and simplifies code structure.
```r
polls_us_election_2016 %>%
filter(!is.na(samplesize)) %>%
group_by(pollster, state) %>%
summarise(
n = n()
)
```
**Tip**: Use Shift + Ctrl/Cmd + M as a shortcut for the pipe operator.
---
class: section-slide
name: tidy-verbs
# **Tidy Verbs**
<html><div style='float:left'></div><hr color='#D38C28' size=1px width=1100px></html>
---
# Tidy Verbs
The Tidyverse packages are a great tool to **tidy data** and perform operations on **tidy data **
<img src="img/tidy_data.png" width="800px" style="display: block; margin: auto;" />
---
# Tidy Verbs
The `tidyverse` ecosystem is composed of multiple packages, each equipped with specific "verbs" to streamline the data workflow process. We'll focus on the verbs from two pivotal packages: `tidyr` and `dplyr`.
* You are ***highly encouraged*** to read through [Hadley Wickham's chapter](https://r4ds.had.co.nz/transform.html). It's clear and concise.
* Also check out these great "cheatsheets" [dplyr](https://github.com/rstudio/cheatsheets/blob/master/data-transformation.pdf) and [tidyr](https://github.com/rstudio/cheatsheets/blob/main/tidyr.pdf).
---
# Tidy Verbs
* The packages are organized around a set of **verbs**, i.e. *actions* to be taken.
* We operate on `data.frames` or `tibbles` (*nicer looking* data.frames.)
--
* All *verbs* work as follows:
`$$\text{verb}(\underbrace{\text{data.frame}}_{\text{1st argument}}, \underbrace{\text{what to do}}_\text{2nd argument})$$`
--
* Alternatively you can (**should**) use the `pipe` operator `%>%`:
`$$\underbrace{\text{data.frame}}_{\text{1st argument}} \underbrace{\text{ %>% }}_{\text{"pipe" operator}} \text{verb}(\underbrace{\text{what to do}}_\text{2nd argument})$$`
---
# Main `tidyr` Verbs
* `tidyr` is designed to tidy your data.
1. `pivot_longer()`: Lengthens data, increasing the number of rows and decreasing the number of columns.
--
1. `pivot_wider()`: Widens data, increasing the number of columns and decreasing the number of rows.
--
1. `separate()`: Splits a column into multiple columns.
--
1. `unite()`: Combines multiple columns into a single column.
--
* These verbs help transform data frames or tibbles to a tidy format, where each variable is a column, each observation is a row, and each type of observational unit forms a table.
---
# `tidyr::pivot_longer()`
Some of the **most useful** verbs in the tidyverse package, and particularly important to achieve tidy data, are the reshape verbs.
The first reshape operation involves making datasets longer by increasing the number of rows and decreasing the number of columns.
<img src="img/pivot_longer.png" width="1000px" style="display: block; margin: auto;" />
---
# `tidyr::pivot_longer()`
**Example:** we have rawpoll and adjpoll for every candidate in a wide format. Perhaps we want to have this information in two variables (instead of 8)
<img src="img/example_long.png" width="1000px" style="display: block; margin: auto;" />
---
# `tidyr::pivot_longer()`
```r
polls_us_election_2016 %>%
* pivot_longer(
* cols = c(rawpoll_clinton:adjpoll_trump),
* names_to = c(".value", "candidate"),
* names_pattern = "(rawpoll|adjpoll)_(.*)"
)
```
<img src="img/example_long_res.png" width="800px" style="display: block; margin: auto;" />
---
# `tidyr::pivot_wider()`
This is the contrary of the previous command, there are cases where we have information in a long format and we would like to make it wider.
<img src="img/pivot_wider.png" width="800px" style="display: block; margin: auto;" />
---
# `tidyr::pivot_wider()`
**Example:** For simplicity, I will wide the previous dataframe, but [here](https://r4ds.hadley.nz/data-tidy.html) you can find multiple examples.
```r
wider_dataframes <- longer_dataframe %>%
* pivot_wider(
* names_from = candidate,
* values_from = c(rawpoll, adjpoll),
values_fn = list
)
```
---
# `tidyr::separate()`
Splits a column into multiple columns
**Example:** Divide enddate into year, month and day.
```r
polls_us_election_2016 %>%
* separate(enddate, into = c("year", "month", "day"), sep = "-")
```
```
## # A tibble: 4,208 × 17
## state startdate year month day pollster grade samplesize population
## <fct> <date> <chr> <chr> <chr> <fct> <fct> <int> <chr>
## 1 U.S. 2016-11-03 2016 11 06 ABC News… A+ 2220 lv
## 2 U.S. 2016-11-01 2016 11 07 Google C… B 26574 lv
## 3 U.S. 2016-11-02 2016 11 06 Ipsos A- 2195 lv
## 4 U.S. 2016-11-04 2016 11 07 YouGov B 3677 lv
## 5 U.S. 2016-11-03 2016 11 06 Gravis M… B- 16639 rv
## 6 U.S. 2016-11-03 2016 11 06 Fox News… A 1295 lv
## 7 U.S. 2016-11-02 2016 11 06 CBS News… A- 1426 lv
## 8 U.S. 2016-11-03 2016 11 05 NBC News… A- 1282 lv
## 9 New Mexico 2016-11-06 2016 11 06 Zia Poll <NA> 8439 lv
## 10 U.S. 2016-11-04 2016 11 07 IBD/TIPP A- 1107 lv
## # ℹ 4,198 more rows
## # ℹ 8 more variables: rawpoll_clinton <dbl>, rawpoll_trump <dbl>,
## # rawpoll_johnson <dbl>, rawpoll_mcmullin <dbl>, adjpoll_clinton <dbl>,
## # adjpoll_trump <dbl>, adjpoll_johnson <dbl>, adjpoll_mcmullin <dbl>
```
---
# `tidyr::unite()`
Combines multiple columns into a single column.
**Example:** Using the previous example, unite the "year", "month", "day" back into "enddate"
```r
separated_data %>%
* unite("enddate", c("year", "month", "day"), sep = "-")
```
```
## # A tibble: 4,208 × 15
## state startdate enddate pollster grade samplesize population rawpoll_clinton
## <fct> <date> <chr> <fct> <fct> <int> <chr> <dbl>
## 1 U.S. 2016-11-03 2016-1… ABC New… A+ 2220 lv 47
## 2 U.S. 2016-11-01 2016-1… Google … B 26574 lv 38.0
## 3 U.S. 2016-11-02 2016-1… Ipsos A- 2195 lv 42
## 4 U.S. 2016-11-04 2016-1… YouGov B 3677 lv 45
## 5 U.S. 2016-11-03 2016-1… Gravis … B- 16639 rv 47
## 6 U.S. 2016-11-03 2016-1… Fox New… A 1295 lv 48
## 7 U.S. 2016-11-02 2016-1… CBS New… A- 1426 lv 45
## 8 U.S. 2016-11-03 2016-1… NBC New… A- 1282 lv 44
## 9 New … 2016-11-06 2016-1… Zia Poll <NA> 8439 lv 46
## 10 U.S. 2016-11-04 2016-1… IBD/TIPP A- 1107 lv 41.2
## # ℹ 4,198 more rows
## # ℹ 7 more variables: rawpoll_trump <dbl>, rawpoll_johnson <dbl>,
## # rawpoll_mcmullin <dbl>, adjpoll_clinton <dbl>, adjpoll_trump <dbl>,
## # adjpoll_johnson <dbl>, adjpoll_mcmullin <dbl>
```
---
# Main `dplyr` Verbs
- `dplyr` helps you with the main data manipulation challenges.
1. `select()`: Choose certain variables by name
--
1. `filter()`: Subset observations based on a certain condition.
--
1. `arrange()`: Reorder rows based on a certain condition.
--
1. `mutate()`: Create new variables.
--
1. `summarise()`: Collapse data to a single summary
--
1. `group_by()`: All the above can be used in conjunction with `group_by()` to use function on groups rather than entire data
---
# `dplyr::select()`
*Example:* Only keep the variables `state, startdate, enddate, pollster, rawpoll_clinton, rawpoll_trump`
```r
polls_us_election_2016 %>%
* select(state,startdate,enddate,pollster,rawpoll_clinton,rawpoll_trump)
```
```
## # A tibble: 4,208 × 6
## state startdate enddate pollster rawpoll_clinton rawpoll_trump
## <fct> <date> <date> <fct> <dbl> <dbl>
## 1 U.S. 2016-11-03 2016-11-06 ABC News/Wash… 47 43
## 2 U.S. 2016-11-01 2016-11-07 Google Consum… 38.0 35.7
## 3 U.S. 2016-11-02 2016-11-06 Ipsos 42 39
## 4 U.S. 2016-11-04 2016-11-07 YouGov 45 41
## 5 U.S. 2016-11-03 2016-11-06 Gravis Market… 47 43
## 6 U.S. 2016-11-03 2016-11-06 Fox News/Ande… 48 44
## 7 U.S. 2016-11-02 2016-11-06 CBS News/New … 45 41
## 8 U.S. 2016-11-03 2016-11-05 NBC News/Wall… 44 40
## 9 New Mexico 2016-11-06 2016-11-06 Zia Poll 46 44
## 10 U.S. 2016-11-04 2016-11-07 IBD/TIPP 41.2 42.7
## # ℹ 4,198 more rows
```
---
# `dplyr::filter()`
*Example:* Which polls had a sample size of at least 2,000 people?
--
```r
*polls_us_election_2016
```
```
## # A tibble: 4,208 × 15
## state startdate enddate pollster grade samplesize population
## <fct> <date> <date> <fct> <fct> <int> <chr>
## 1 U.S. 2016-11-03 2016-11-06 ABC News/Washin… A+ 2220 lv
## 2 U.S. 2016-11-01 2016-11-07 Google Consumer… B 26574 lv
## 3 U.S. 2016-11-02 2016-11-06 Ipsos A- 2195 lv
## 4 U.S. 2016-11-04 2016-11-07 YouGov B 3677 lv
## 5 U.S. 2016-11-03 2016-11-06 Gravis Marketing B- 16639 rv
## 6 U.S. 2016-11-03 2016-11-06 Fox News/Anders… A 1295 lv
## 7 U.S. 2016-11-02 2016-11-06 CBS News/New Yo… A- 1426 lv
## 8 U.S. 2016-11-03 2016-11-05 NBC News/Wall S… A- 1282 lv
## 9 New Mexico 2016-11-06 2016-11-06 Zia Poll <NA> 8439 lv
## 10 U.S. 2016-11-04 2016-11-07 IBD/TIPP A- 1107 lv
## # ℹ 4,198 more rows
## # ℹ 8 more variables: rawpoll_clinton <dbl>, rawpoll_trump <dbl>,
## # rawpoll_johnson <dbl>, rawpoll_mcmullin <dbl>, adjpoll_clinton <dbl>,
## # adjpoll_trump <dbl>, adjpoll_johnson <dbl>, adjpoll_mcmullin <dbl>
```
---
# `dplyr::filter()`
*Example:* Which polls had a sample size of at least 2,000 people?
```r
polls_us_election_2016 %>%
* filter(samplesize > 2000)
```
```
## # A tibble: 403 × 15
## state startdate enddate pollster grade samplesize population
## <fct> <date> <date> <fct> <fct> <int> <chr>
## 1 U.S. 2016-11-03 2016-11-06 ABC News/Washin… A+ 2220 lv
## 2 U.S. 2016-11-01 2016-11-07 Google Consumer… B 26574 lv
## 3 U.S. 2016-11-02 2016-11-06 Ipsos A- 2195 lv
## 4 U.S. 2016-11-04 2016-11-07 YouGov B 3677 lv
## 5 U.S. 2016-11-03 2016-11-06 Gravis Marketing B- 16639 rv
## 6 New Mexico 2016-11-06 2016-11-06 Zia Poll <NA> 8439 lv
## 7 U.S. 2016-11-05 2016-11-07 The Times-Picay… <NA> 2521 lv
## 8 U.S. 2016-11-01 2016-11-07 USC Dornsife/LA… <NA> 2972 lv
## 9 Georgia 2016-11-03 2016-11-06 Gravis Marketing B- 2002 rv
## 10 Virginia 2016-11-01 2016-11-02 Remington <NA> 3076 lv
## # ℹ 393 more rows
## # ℹ 8 more variables: rawpoll_clinton <dbl>, rawpoll_trump <dbl>,
## # rawpoll_johnson <dbl>, rawpoll_mcmullin <dbl>, adjpoll_clinton <dbl>,
## # adjpoll_trump <dbl>, adjpoll_johnson <dbl>, adjpoll_mcmullin <dbl>
```
---
# `dplyr::filter()`
Standard suite of comparison operators:
- `>`: greater than,
- `<`: smaller than,
- `>=`: greater than or equal to,
- `<=`: smaller than or equal to,
- `!=`: not equal to,
- `==`: equal to.
Logical operators:
1. `x & y`: `x` **and** `y`
1. `x | y`: `x` **or** `y`
1. `!y`: **not** `y`
---
# `dplyr::filter()`
*Example:* Which A graded poll with at least 2,000 people had Trump win at least 45% of the vote?
```r
polls_us_election_2016 %>%
* filter(grade == "A" & samplesize > 2000 & rawpoll_trump > 45)
```
```
## # A tibble: 1 × 15
## state startdate enddate pollster grade samplesize population
## <fct> <date> <date> <fct> <fct> <int> <chr>
## 1 Indiana 2016-04-26 2016-04-28 Marist College A 2149 rv
## # ℹ 8 more variables: rawpoll_clinton <dbl>, rawpoll_trump <dbl>,
## # rawpoll_johnson <dbl>, rawpoll_mcmullin <dbl>, adjpoll_clinton <dbl>,
## # adjpoll_trump <dbl>, adjpoll_johnson <dbl>, adjpoll_mcmullin <dbl>
```
---
# `dplyr::arrange()`
*Example:* Sort the dataframe in terms of the sample size.
```r
polls_us_election_2016 %>%
arrange(samplesize) # this will do it from smaller to larger by default
```
```
## # A tibble: 4,208 × 15
## state startdate enddate pollster grade samplesize population
## <fct> <date> <date> <fct> <fct> <int> <chr>
## 1 Wyoming 2016-10-04 2016-10-09 Google Consu… B 35 lv
## 2 Maine 2016-10-04 2016-10-09 Google Consu… B 37 lv
## 3 New Hampshire 2016-09-21 2016-09-26 Google Consu… B 39 lv
## 4 Hawaii 2016-09-14 2016-09-20 Google Consu… B 42 lv
## 5 Wyoming 2016-09-27 2016-10-03 Google Consu… B 43 lv
## 6 Rhode Island 2016-10-10 2016-10-14 Google Consu… B 45 lv
## 7 Vermont 2016-10-04 2016-10-09 Google Consu… B 47 lv
## 8 North Dakota 2016-09-27 2016-10-03 Google Consu… B 49 lv
## 9 Rhode Island 2016-09-14 2016-09-20 Google Consu… B 50 lv
## 10 Rhode Island 2016-10-04 2016-10-09 Google Consu… B 51 lv
## # ℹ 4,198 more rows
## # ℹ 8 more variables: rawpoll_clinton <dbl>, rawpoll_trump <dbl>,
## # rawpoll_johnson <dbl>, rawpoll_mcmullin <dbl>, adjpoll_clinton <dbl>,
## # adjpoll_trump <dbl>, adjpoll_johnson <dbl>, adjpoll_mcmullin <dbl>
```
---
# `dplyr::mutate()`
*Example:* What was...
1. the combined vote share of Trump and Clinton for each poll?
2. the difference between Trump's raw poll vote share and 538's adjusted vote share?
```r
polls_us_election_2016 %>%
* mutate(trump_clinton_tot = rawpoll_trump + rawpoll_clinton,
* trump_raw_adj_diff = rawpoll_trump - adjpoll_trump)
```
```
## # A tibble: 4,208 × 17
## state startdate enddate pollster grade samplesize population
## <fct> <date> <date> <fct> <fct> <int> <chr>
## 1 U.S. 2016-11-03 2016-11-06 ABC News/Washin… A+ 2220 lv
## 2 U.S. 2016-11-01 2016-11-07 Google Consumer… B 26574 lv
## 3 U.S. 2016-11-02 2016-11-06 Ipsos A- 2195 lv
## 4 U.S. 2016-11-04 2016-11-07 YouGov B 3677 lv
## 5 U.S. 2016-11-03 2016-11-06 Gravis Marketing B- 16639 rv
## 6 U.S. 2016-11-03 2016-11-06 Fox News/Anders… A 1295 lv
## 7 U.S. 2016-11-02 2016-11-06 CBS News/New Yo… A- 1426 lv
## 8 U.S. 2016-11-03 2016-11-05 NBC News/Wall S… A- 1282 lv
## 9 New Mexico 2016-11-06 2016-11-06 Zia Poll <NA> 8439 lv
## 10 U.S. 2016-11-04 2016-11-07 IBD/TIPP A- 1107 lv
## # ℹ 4,198 more rows
## # ℹ 10 more variables: rawpoll_clinton <dbl>, rawpoll_trump <dbl>,
## # rawpoll_johnson <dbl>, rawpoll_mcmullin <dbl>, adjpoll_clinton <dbl>,
## # adjpoll_trump <dbl>, adjpoll_johnson <dbl>, adjpoll_mcmullin <dbl>,
## # trump_clinton_tot <dbl>, trump_raw_adj_diff <dbl>
```
---
# `dplyr::mutate()`
*Example:* What was...
1. the combined vote share of Trump and Clinton for each poll?
2. the difference between Trump's raw poll vote share and 538's adjusted vote share?
```r
polls_us_election_2016 %>%
mutate(trump_clinton_tot = rawpoll_trump + rawpoll_clinton,
trump_raw_adj_diff = rawpoll_trump - adjpoll_trump) %>%
* names()
```
```
## [1] "state" "startdate" "enddate"
## [4] "pollster" "grade" "samplesize"
## [7] "population" "rawpoll_clinton" "rawpoll_trump"
## [10] "rawpoll_johnson" "rawpoll_mcmullin" "adjpoll_clinton"
## [13] "adjpoll_trump" "adjpoll_johnson" "adjpoll_mcmullin"
## [16] "trump_clinton_tot" "trump_raw_adj_diff"
```
---
# `dplyr::summarise()`
Compute statistics
*Example:* What is the maximum vote share for Trump?
```r
polls_us_election_2016 %>%
* summarise(max_trump = max(rawpoll_trump))
```
```
## # A tibble: 1 × 1
## max_trump
## <dbl>
## 1 68
```
---
# `dplyr::group_by()`
*Example:* What is the average vote share for Clinton by poll grade?
```r
polls_us_election_2016 %>%
* group_by(grade)
```
```
## # A tibble: 4,208 × 15
## # Groups: grade [11]
## state startdate enddate pollster grade samplesize population
## <fct> <date> <date> <fct> <fct> <int> <chr>
## 1 U.S. 2016-11-03 2016-11-06 ABC News/Washin… A+ 2220 lv
## 2 U.S. 2016-11-01 2016-11-07 Google Consumer… B 26574 lv
## 3 U.S. 2016-11-02 2016-11-06 Ipsos A- 2195 lv
## 4 U.S. 2016-11-04 2016-11-07 YouGov B 3677 lv
## 5 U.S. 2016-11-03 2016-11-06 Gravis Marketing B- 16639 rv
## 6 U.S. 2016-11-03 2016-11-06 Fox News/Anders… A 1295 lv
## 7 U.S. 2016-11-02 2016-11-06 CBS News/New Yo… A- 1426 lv
## 8 U.S. 2016-11-03 2016-11-05 NBC News/Wall S… A- 1282 lv
## 9 New Mexico 2016-11-06 2016-11-06 Zia Poll <NA> 8439 lv
## 10 U.S. 2016-11-04 2016-11-07 IBD/TIPP A- 1107 lv
## # ℹ 4,198 more rows
## # ℹ 8 more variables: rawpoll_clinton <dbl>, rawpoll_trump <dbl>,
## # rawpoll_johnson <dbl>, rawpoll_mcmullin <dbl>, adjpoll_clinton <dbl>,
## # adjpoll_trump <dbl>, adjpoll_johnson <dbl>, adjpoll_mcmullin <dbl>
```
---
# `dplyr::group_by()`
*Example:* What is the average vote share for Clinton by poll grade?
```r
polls_us_election_2016 %>%
* group_by(grade)
```
```
## # A tibble: 4,208 × 15
## # Groups: grade [11]
## state startdate enddate pollster grade samplesize population
## <fct> <date> <date> <fct> <fct> <int> <chr>
## 1 U.S. 2016-11-03 2016-11-06 ABC News/Washin… A+ 2220 lv
## 2 U.S. 2016-11-01 2016-11-07 Google Consumer… B 26574 lv
## 3 U.S. 2016-11-02 2016-11-06 Ipsos A- 2195 lv
## 4 U.S. 2016-11-04 2016-11-07 YouGov B 3677 lv
## 5 U.S. 2016-11-03 2016-11-06 Gravis Marketing B- 16639 rv
## 6 U.S. 2016-11-03 2016-11-06 Fox News/Anders… A 1295 lv
## 7 U.S. 2016-11-02 2016-11-06 CBS News/New Yo… A- 1426 lv
## 8 U.S. 2016-11-03 2016-11-05 NBC News/Wall S… A- 1282 lv
## 9 New Mexico 2016-11-06 2016-11-06 Zia Poll <NA> 8439 lv
## 10 U.S. 2016-11-04 2016-11-07 IBD/TIPP A- 1107 lv
## # ℹ 4,198 more rows
## # ℹ 8 more variables: rawpoll_clinton <dbl>, rawpoll_trump <dbl>,
## # rawpoll_johnson <dbl>, rawpoll_mcmullin <dbl>, adjpoll_clinton <dbl>,
## # adjpoll_trump <dbl>, adjpoll_johnson <dbl>, adjpoll_mcmullin <dbl>
```
---
# `dplyr::group_by()`
*Example:* What is the average vote share for Clinton by poll grade?
```r
polls_us_election_2016 %>%
group_by(grade) %>%
* summarise(mean_vote_clinton = mean(rawpoll_clinton))
```
```
## # A tibble: 11 × 2
## grade mean_vote_clinton
## <fct> <dbl>
## 1 D 46.7
## 2 C- 43.2
## 3 C 41.8
## 4 C+ 44.2
## 5 B- 43.9
## 6 B 37.3
## 7 B+ 44.1
## 8 A- 43.0
## 9 A 45.3
## 10 A+ 45.8
## 11 <NA> 43.2
```
---
# Chaining commands
With these verbs and the pipe chaining commands helps tidy your workflow, you can do multiple of this operations at the same time.
(for tidyverse verbs and others)
```r
polls_us_election_2016 %>%
* pivot_longer(
cols = c(rawpoll_clinton:adjpoll_mcmullin),
names_to = c(".value", "candidate"),
names_pattern = "(rawpoll|adjpoll)_(.*)"
) %>% # reshape
select(-enddate) %>% # everything except enddate
filter(samplesize>=2000) %>% # filter sample size greater than 2,000
group_by(state, candidate) %>% #group by state and candidate
summarise(rawpoll = mean(rawpoll, na.rm = TRUE)) # summarise
```
```
## # A tibble: 104 × 3
## # Groups: state [26]
## state candidate rawpoll
## <fct> <chr> <dbl>
## 1 Alabama clinton 32.5
## 2 Alabama johnson NaN
## 3 Alabama mcmullin NaN
## 4 Alabama trump 62.5
## 5 Arizona clinton 44
## 6 Arizona johnson 7.5
## 7 Arizona mcmullin NaN
## 8 Arizona trump 42.8
## 9 California clinton 54.2
## 10 California johnson 7.32
## # ℹ 94 more rows
```
---
# Chaining commands
With these verbs and the pipe chaining commands helps tidy your workflow, you can do multiple of this operations at the same time.
(for tidyverse verbs and others)
```r
polls_us_election_2016 %>%
* pivot_longer(
cols = c(rawpoll_clinton:adjpoll_mcmullin),
names_to = c(".value", "candidate"),
names_pattern = "(rawpoll|adjpoll)_(.*)"
) # reshape
```
```
## # A tibble: 16,832 × 10
## state startdate enddate pollster grade samplesize population candidate
## <fct> <date> <date> <fct> <fct> <int> <chr> <chr>
## 1 U.S. 2016-11-03 2016-11-06 ABC News/W… A+ 2220 lv clinton
## 2 U.S. 2016-11-03 2016-11-06 ABC News/W… A+ 2220 lv trump
## 3 U.S. 2016-11-03 2016-11-06 ABC News/W… A+ 2220 lv johnson
## 4 U.S. 2016-11-03 2016-11-06 ABC News/W… A+ 2220 lv mcmullin
## 5 U.S. 2016-11-01 2016-11-07 Google Con… B 26574 lv clinton
## 6 U.S. 2016-11-01 2016-11-07 Google Con… B 26574 lv trump
## 7 U.S. 2016-11-01 2016-11-07 Google Con… B 26574 lv johnson
## 8 U.S. 2016-11-01 2016-11-07 Google Con… B 26574 lv mcmullin
## 9 U.S. 2016-11-02 2016-11-06 Ipsos A- 2195 lv clinton
## 10 U.S. 2016-11-02 2016-11-06 Ipsos A- 2195 lv trump
## # ℹ 16,822 more rows
## # ℹ 2 more variables: rawpoll <dbl>, adjpoll <dbl>
```
---
# Chaining commands
With these verbs and the pipe chaining commands helps tidy your workflow, you can do multiple of this operations at the same time.
(for tidyverse verbs and others)
```r
polls_us_election_2016 %>%
pivot_longer(
cols = c(rawpoll_clinton:adjpoll_mcmullin),
names_to = c(".value", "candidate"),
names_pattern = "(rawpoll|adjpoll)_(.*)"
) %>% # reshape
* select(-enddate) # everything except enddate
```
```
## # A tibble: 16,832 × 9
## state startdate pollster grade samplesize population candidate rawpoll
## <fct> <date> <fct> <fct> <int> <chr> <chr> <dbl>
## 1 U.S. 2016-11-03 ABC News/Wash… A+ 2220 lv clinton 47
## 2 U.S. 2016-11-03 ABC News/Wash… A+ 2220 lv trump 43
## 3 U.S. 2016-11-03 ABC News/Wash… A+ 2220 lv johnson 4
## 4 U.S. 2016-11-03 ABC News/Wash… A+ 2220 lv mcmullin NA
## 5 U.S. 2016-11-01 Google Consum… B 26574 lv clinton 38.0
## 6 U.S. 2016-11-01 Google Consum… B 26574 lv trump 35.7
## 7 U.S. 2016-11-01 Google Consum… B 26574 lv johnson 5.46
## 8 U.S. 2016-11-01 Google Consum… B 26574 lv mcmullin NA
## 9 U.S. 2016-11-02 Ipsos A- 2195 lv clinton 42
## 10 U.S. 2016-11-02 Ipsos A- 2195 lv trump 39
## # ℹ 16,822 more rows
## # ℹ 1 more variable: adjpoll <dbl>
```
---
# Chaining commands
With these verbs and the pipe chaining commands helps tidy your workflow, you can do multiple of this operations at the same time.
(for tidyverse verbs and others)
```r
polls_us_election_2016 %>%
pivot_longer(
cols = c(rawpoll_clinton:adjpoll_mcmullin),
names_to = c(".value", "candidate"),
names_pattern = "(rawpoll|adjpoll)_(.*)"
) %>% # reshape
select(-enddate) %>% # everything except enddate
* filter(samplesize>=2000) # filter sample size greater than 2,000
```
```