-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathr-for-data-science-sections-11-through-20.rmd
4689 lines (3594 loc) · 129 KB
/
r-for-data-science-sections-11-through-20.rmd
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
---
title: "R-For-Data-Science-§11:§20"
author: "Evan-Woods"
date: "2023-11-10"
output: github_document
always_allow_html: true
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## Libraries
```{r}
if (!require(dplyr)) install.packages("dplyr")
# if (!require(stargazer)) install.packages("stargazer")
if (!require(tidyverse)) install.packages("tidyverse")
if(!require(nycflights13)) install.packages("nycflights13")
# if (!require(shiny)) install.packages("shiny")
# if(!require(Lahman)) install.packages("Lahman")
if(!require(ggplot2)) install.packages("ggplot2")
# if(!require(EnvStats)) install.packages("EnvStats")
# library(EnvStats)
library(tidyverse)
```
## Section 11: Data Import
```{r}
# e_woods_matrix <- read_csv("trait_matrix.xlsx - Sheet 1.csv")
# deepa_matrix <- read_csv("Candidate Rankings.xlsx - Sheet1.csv")
# health <- read_csv("HealthAutoExport-2023-10-29-2023-11-05.json")
# eye_classification <- read_csv("EEG_Eye_State_Classification.csv")
# Define the character as na
read_csv("a,b,c\n1,2,.", na=".")
# Drop lines that start with a comment
read_csv("# this is a comment\na,b,c\n1,2,.", comment = "#", na = ".")
read_csv("# this is a comment
This is the second line of data
\na,b,c\n1,2,.", comment = "#", na = ".")
# Passing column names as a character vector
read_csv("1,2,3\n4,5,6,", col_names = c("x", "y", "z"))
```
#### 11.2.2 Exercises
```{r}
# read_delim will be used for "|" delimited files
# read_csv and read_tsv have all arguments in common.
# The most important arguments to read_fwf() are the file, col_positions, and col_types
# pass in quote to read_csv to specify quotes
# 5 there are only two columns
read_csv("a,b\n1,2,3\n4,5,6") # reads this as a:1 , b:23
# the column rows are not the same
read_csv("a,b,c\n1,2\n1,2,3,4") # column c on row 1 is NA and 34 on row 2
#
```
### 11.3 Parsing
```{r}
# All data can be parsed. The types of parsing includes:
# parse_number
# parse_character
# parse_factor
# parse_datetime
# parse_logical
# parse_double
# Parsing will handle character encodings, and locale so as to represent clean data.
# use guess_encoding() to guess the encoding of a character string
```
#### 11.3.5 Exercises
```{r}
# The most important arguments to locale are date_names, date_format, decimal_mark, & tz
# There is an error that decimal_mark & grouping mark must be different if both are the same.
#parse_double("1,23", locale = locale(decimal_mark = ",", grouping_mark = (",")))
#
parse_date("01/02/15", "%m/%d/%y")
```
### Section 12: Tidy Data
### Section 12.2.1 Exercises:
```{r}
table1
#> # A tibble: 6 × 4
#> country year cases population
#> <chr> <dbl> <dbl> <dbl>
#> 1 Afghanistan 1999 745 19987071
#> 2 Afghanistan 2000 2666 20595360
#> 3 Brazil 1999 37737 172006362
#> 4 Brazil 2000 80488 174504898
#> 5 China 1999 212258 1272915272
#> 6 China 2000 213766 1280428583
table2
#> # A tibble: 12 × 4
#> country year type count
#> <chr> <dbl> <chr> <dbl>
#> 1 Afghanistan 1999 cases 745
#> 2 Afghanistan 1999 population 19987071
#> 3 Afghanistan 2000 cases 2666
#> 4 Afghanistan 2000 population 20595360
#> 5 Brazil 1999 cases 37737
#> 6 Brazil 1999 population 172006362
#> # ℹ 6 more rows
table3
#> # A tibble: 6 × 3
#> country year rate
#> <chr> <dbl> <chr>
#> 1 Afghanistan 1999 745/19987071
#> 2 Afghanistan 2000 2666/20595360
#> 3 Brazil 1999 37737/172006362
#> 4 Brazil 2000 80488/174504898
#> 5 China 1999 212258/1272915272
#> 6 China 2000 213766/1280428583
# Spread across two tibbles
table4a # cases
#> # A tibble: 3 × 3
#> country `1999` `2000`
#> <chr> <dbl> <dbl>
#> 1 Afghanistan 745 2666
#> 2 Brazil 37737 80488
#> 3 China 212258 213766
table4b # population
#> # A tibble: 3 × 3
#> country `1999` `2000`
#> <chr> <dbl> <dbl>
#> 1 Afghanistan 19987071 20595360
#> 2 Brazil 172006362 174504898
#> 3 China 1272915272 1280428583
```
```{r}
# Quesion 1
# Table 1 organizes its columns by country, year, cases, and population. It organizes its rows numerically where each row represents data that is associated with a country. The data within the table are individual values.
table1
#> # A tibble: 6 × 4
#> country year cases population
#> <chr> <dbl> <dbl> <dbl>
#> 1 Afghanistan 1999 745 19987071
#> 2 Afghanistan 2000 2666 20595360
#> 3 Brazil 1999 37737 172006362
#> 4 Brazil 2000 80488 174504898
#> 5 China 1999 212258 1272915272
#> 6 China 2000 213766 1280428583
#>
# Table 2 organizes its columns by country, year, type, & count. The rows are organized with cases and population variables in the type column. Each cell contains only one item which is either a variable or a name of a variable. This data is not tidy.
table2
#> # A tibble: 12 × 4
#> country year type count
#> <chr> <dbl> <chr> <dbl>
#> 1 Afghanistan 1999 cases 745
#> 2 Afghanistan 1999 population 19987071
#> 3 Afghanistan 2000 cases 2666
#> 4 Afghanistan 2000 population 20595360
#> 5 Brazil 1999 cases 37737
#> 6 Brazil 1999 population 172006362
#> # ℹ 6 more rows
# Table 3 organizes its columns by country, year, & rate. The rows are organized by country. The rate column variables for each country contains values that are comprised of the count of cases divided by the population count. This data is not tidy. To tidy this data, I suggest adding the count of cases and population as columns and using the distinct values in these columns for rate.
table3
#> # A tibble: 6 × 3
#> country year rate
#> <chr> <dbl> <chr>
#> 1 Afghanistan 1999 745/19987071
#> 2 Afghanistan 2000 2666/20595360
#> 3 Brazil 1999 37737/172006362
#> 4 Brazil 2000 80488/174504898
#> 5 China 1999 212258/1272915272
#> 6 China 2000 213766/1280428583
#>
#>
# Table 4a & 4b contain tibbles such that the column names are country, `1999`, & `2000`. The rows are individual countries in both tibbles. The values in the tibbles are individual values. This data is not tidy because the column names are variables themselves: 1999 & 2000 are "year" variables. Furthermore, the data is split between two tibbles.
# Spread across two tibbles
table4a # cases
#> # A tibble: 3 × 3
#> country `1999` `2000`
#> <chr> <dbl> <dbl>
#> 1 Afghanistan 745 2666
#> 2 Brazil 37737 80488
#> 3 China 212258 213766
table4b # population
#> # A tibble: 3 × 3
#> country `1999` `2000`
#> <chr> <dbl> <dbl>
#> 1 Afghanistan 19987071 20595360
#> 2 Brazil 172006362 174504898
#> 3 China 1272915272 1280428583
```
```{r}
# Compute rate for table2 and table4a and table4b
# Extract the number of TB cases per country per year From table2.
n_cases_per_country <- table2 %>% group_by(type_cases = type == "cases") %>% filter(type_cases == TRUE) %>% group_by(country) %>% summarise(n_cases = sum(count))
```
```{r}
# Compute rate for table2 and table4a and table4b
n_years_per_country <- table2 %>% group_by(type_cases = type == "cases") %>% filter(type_cases == TRUE) %>% group_by(country, year) %>% summarise() %>% summarise(n_years = n())
countries <- table2 %>% group_by(type_cases = type == "cases") %>% filter(type_cases == TRUE) %>% group_by(country) %>% summarise()
n_cases_per_year_per_country <- (n_cases_per_country$n_cases / n_years_per_country$n_years)
(n_cases_per_year_per_country_tb <- tibble(countries, n_cases_per_year_per_country))
# Extract the number of TB cases per country per year from tables 4a & 4b.
countries <- table4a[["country"]]
(counts_1999 <- table4a[["1999"]])
(counts_2000 <- table4a[["2000"]])
(counts_per_year <- (counts_1999 + counts_2000) / 2)
(n_counts_per_country_per_year_4a <- tibble(countries, counts_per_year))
```
```{r 2.2 Extract the matching population per country per year for table2 and table4a and table4b}
# table 2
n_population_per_country <- table2 %>% group_by(type_cases = type == "population") %>% filter(type_cases == TRUE) %>% group_by(country) %>% summarise(n_population = sum(count))
n_years_per_country <- table2 %>% group_by(type_cases = type == "cases") %>% filter(type_cases == TRUE) %>% group_by(country, year) %>% summarise() %>% summarise(n_years = n())
countries <- table2 %>% group_by(type_cases = type == "cases") %>% filter(type_cases == TRUE) %>% group_by(country) %>% summarise()
n_population_per_year_per_country <- (n_population_per_country$n_population / n_years_per_country$n_years)
n_population_per_year_per_country_tb <- tibble(countries, n_population_per_year_per_country)
# Table4b
# population
(countries_4b <- table4b[["country"]])
(population_1999_4b <- table4b[["1999"]])
(population_2000_4b <- table4b[["2000"]])
population_per_year_4b <- (population_1999_4b + population_2000_4b) / 2
n_population_per_year_per_country_4b <- tibble(countries_4b, population_per_year_4b)
(n_population_per_year_per_country_4b)
```
```{r 2.3 Divide cases by population, and multiply by 10000 for table2 and table4a and table4b}
# Table 2
(n_cases_per_year_per_country_tb)
(n_population_per_year_per_country_tb)
(rate_table2 <- (n_cases_per_year_per_country_tb$n_cases_per_year_per_country / n_population_per_year_per_country_tb$n_population_per_year_per_country) * 10000)
(rate_table4a4b <- (n_counts_per_country_per_year_4a$counts_per_year / n_population_per_year_per_country_4b$population_per_year_4b) * 10000)
```
```{r Store back in the appropriate place}
table2
rate_table2
rate_table2_formatted <- c(rate_table2[[1]], rate_table2[[1]], rate_table2[[1]], rate_table2[[1]],rate_table2[[2]], rate_table2[[2]], rate_table2[[2]], rate_table2[[2]],rate_table2[[3]], rate_table2[[3]], rate_table2[[3]], rate_table2[[3]])
table2[["rate"]] = rate_table2_formatted
# table2
###
rate_table4a4b
table4a[["rate"]] = rate_table4a4b
table4a
table4b[["rate"]] = rate_table4a4b
table4b
# It was easier to address table4a & 4b; However working with table2 was more efficient. Containing variables in the cells of table2 proved challenging, and the split tibbles proved inefficient.
```
```{r 3 Recreate the plot showing change in cases over time using table2 instead of table1. What do you need to do first?}
# Compute rate per 10,000
table1 %>%
mutate(rate = cases / population * 10000)
#> # A tibble: 6 × 5
#> country year cases population rate
#> <chr> <dbl> <dbl> <dbl> <dbl>
#> 1 Afghanistan 1999 745 19987071 0.373
#> 2 Afghanistan 2000 2666 20595360 1.29
#> 3 Brazil 1999 37737 172006362 2.19
#> 4 Brazil 2000 80488 174504898 4.61
#> 5 China 1999 212258 1272915272 1.67
#> 6 China 2000 213766 1280428583 1.67
# Compute cases per year
table1 %>%
count(year, wt = cases)
#> # A tibble: 2 × 2
#> year n
#> <dbl> <dbl>
#> 1 1999 250740
#> 2 2000 296920
# Visualise changes over time
library(ggplot2)
ggplot(table1, aes(year, cases)) +
geom_line(aes(group = country), colour = "grey50") +
geom_point(aes(colour = country))
# table2 %>% group_by(cases_logical = type == "cases") %>% filter(cases_logical) %>% group_by(year, country) %>% summarise()
(table2_n_cases_per_country_per_year <- table2 %>% group_by(type_cases = type == "cases") %>% filter(type_cases == TRUE) %>% group_by(country))
ggplot(table2_n_cases_per_country_per_year, aes(year, count)) +
geom_line(aes(group = country), color = "grey50") +
geom_point(aes(color = country))
```
```{r}
table4a %>% pivot_longer(c(`1999`, `2000`), names_to = "year", values_to = "counts")
```
```{r}
table2
tidy_table2 <- table2 %>% pivot_wider(names_from = "year", values_from = "count") %>% pivot_longer(c(`1999`, `2000`), names_to = "year", values_to= "count") %>% pivot_wider(names_from = "type", values_from = "count")
tidy_table2
```
### Section 12.3.3 Exercises:
```{r}
# The values in a column become column names after a pivot wider. The outermost column is used as column names for pivot_wider(). pivot_longer() will then place the column names into rows, but will maintain the initial column ordering of the first row. pivot_longer() will not re-order rows.
stocks <- tibble(
year = c(2015, 2015, 2016, 2016),
half = c(1,2,1,2),
return = c(1.88,0.59,0.92, 0.17)
)
```
```{r}
stocks
```
```{r}
stocks %>%
pivot_wider(names_from = year, values_from = return ) %>%
pivot_longer(`2015`:`2016`, names_to = "year", values_to = "return")
```
```{r}
table4a
```
```{r}
table4a
```
```{r}
table4a
```
```{r eval = FALSE}
# table4a %>% pivot_longer(c(1999, 2000), names_to = "year", values_to = "cases")
# The names need to be in backticks because they are numbers. i.e.
#table4a %>%
# pivot_longer(c(1999, 2000), names_to = "year", values_to = "cases")
```
```{r}
# Quesion 3
# Calling wider on this tribble will allow the values to be placed in a double, a column for personid would allow this data to be transformed appropriately.
people <- tribble(
~name, ~names, ~values, ~pid,
#-----------------|--------|---------|----
"Phillip Woods", "age", 45, 1,
"Phillip Woods", "height", 186, 1,
"Phillip Woods", "age", 50, 2,
"Jessica Cordero", "age", 37, 3,
"Jessica Cordero", "height", 156, 3,
)
people %>% group_by(name, names,) %>% summarise(values)
# %>% summarise
# %>% summarise() %>% select(everything())
# Answer:
(people_wider <- people %>% pivot_wider( names_from = names, values_from = values))
# val[["age"]]
# %>% pivot_wider(names_from = name, values_from = values)
```
```{r}
# Quesion 4
preg <- tribble(
~pregnant, ~male, ~female,
"yes", NA, 10,
"no", 20, 12
)
preg %>% pivot_longer(c("male", "female"), names_to = "gender", values_to = "count") %>% select(count, pregnant, gender)
```
## Section 12.4 Separating and Uniting
#### Section 12.4.1 Separate
```{r}
# table3
table3 %>% separate(rate, into = c("count", "population")) %>% separate(year, into = c("century", "year"), sep=2)
```
#### Section 12.4.2 Unite
```{r Unite}
table5 %>%
unite(new, century, year, sep = "")
```
#### Section 12.4.3 Exercises
```{r}
tibble(x = c("a,b,c", "d,e,f,g", "h,i,j")) %>%
separate(x, c("one", "two", "three"), extra = "merge")
tibble(x = c("a,b,c", "d, e", "f, g, i")) %>%
separate(x, c("one", "two", "three"), fill = "left")
```
```{r}
# Quesion 2
# Removes input columns from the output dataframe
```
```{r}
# Quesion 3
# Extract will turn a group into columns. Extract will separate groups into columns as well. Extract has been superceded.
```
## Section 12.5 Missing Values:
```{r}
stocks <- tibble(
year = c(2015, 2015, 2015, 2015, 2016, 2016, 2016),
qtr = c( 1, 2, 3, 4, 2, 3, 4),
return = c(1.88, 0.59, 0.35, NA, 0.92, 0.17, 2.66)
)
```
```{r}
stocks %>% pivot_wider(names_from = year, values_from = return)
```
```{r}
treatment <- tribble(
~ person, ~ treatment, ~response,
"Derrick Whitmore", 1, 7,
NA, 2, 10,
NA, 3, 9,
"Katherine Burke", 1, 4
)
```
```{r}
treatment %>% fill(person)
```
```{r}
# Complete
df <- tibble(
group = c(1:2, 1, 2),
item_id = c(1:2, 2, 3),
item_name = c("a", "a", "b", "b"),
value1 = c(1, NA, 3, 4),
value2 = 4:7
)
df
```
```{r}
df %>% complete(group, item_id, item_name)
```
#### Section 12.5.1 Exercises
```{r}
df %>% complete(group, nesting(item_id, item_name))
# Complete will find all the combinations of elements n a list.
# Fill will fill in missing value with the last observation carried forward.
#
```
```{r}
# Quesion 1
# What does the direction argument to fill do?
treatment %>% fill(person, .direction = "up")
# Direction in fill will fill NA from a particular direction
```
```{r}
who
```
```{r}
who1 <- who %>% pivot_longer(
cols = new_sp_m014:newrel_f65,
names_to = "key",
values_to = "cases",
values_drop_na = TRUE
)
who1
```
```{r}
who1 %>% count(key)
```
```{r}
who2 <- who1 %>%
mutate(key = stringr::str_replace(key, "newrel", "new_rel"))
who2
```
```{r}
who3 <- who2 %>%
separate(key, c("new", "type", "sexage"))
who3
```
```{r}
who3 %>%
count(new)
who4 <- who3 %>%
select(-new, -iso2, -iso3)
```
```{r}
who5 <- who4 %>%
separate(sexage, c("sex", "age"), sep = 1)
who5
```
```{r}
who5 <- who4 %>%
separate(sexage, c("sex", "age"), sep = 1)
who5
```
```{r}
# Checking for implicit missing values
# names()
n_who5 <- who5 %>% pivot_wider(names_from = year, values_from = cases)
n_who5
n_who5 %>% filter(is.na(`1997`))
```
```{r}
# Checking for implicit missing values
# who5 %>% complete(type, sex) %>% filter(is.na(case))
```
```{r}
# Afghanistan sn m 014
# who5 %>% group_by(country, type, sex, age) %>% filter(country == "Afghanistan", type == "sn", sex == "m", age == "014")
# %>% group_by(type) %>% summarise()
# %>% group_by(country) %>% summarise()
# %>%
# complete(country, var, sex, age, cases)
```
```{r}
who %>%
pivot_longer(
cols = new_sp_m014:newrel_f65,
names_to = "key",
values_to = "cases",
values_drop_na = TRUE
) %>%
mutate(
key = stringr::str_replace(key, "newrel", "new_rel")
) %>%
separate(key, c("new", "var", "sexage")) %>%
# select(-new, -iso2, -iso3) %>%
separate(sexage, c("sex", "age"), sep = 1)
```
```{r}
# Quesion 1
# Dropping NA values is necessary in order to create a tidy tibble. Otherwise, the values of cases are "NA". Yes, it is reasonable to drop NA values to ensure that the values that are present in the tibble are valid. On the contrary, dropping NA values could be filled rather than dropped. It is possible to show implicit missing values through the presence of NA values. If these values are dropped, then the implicit missing values in the data may be more challenging to detect as explicit missing values are turned implicit. The difference between NA and zero is that NA represents a value that is missing from the dataset and zero defines a numeric value that is present and recorded as having a value of literally zero. Yes, there are years missing between 1997 and 2000. There are many implicit missing values in the dataset. This can be shown by pivoting the dataset wider to bring the years into a column and then listing the values from cases. The year 1997 has many missing values for cases in Afghanistan for example. See the code snippet below:
# n_who5 <- who5 %>% pivot_wider(names_from = year, values_from = cases)
# n_who5
# n_who5 %>% filter(is.na(`1997`))
```
```{r}
# Quesion 2
# If you neglect the mutate step, data will be missing from the tibble. It will not separate on "new" because there is only the presence of "newrel" and the separator is "_".
who %>%
pivot_longer(
cols = new_sp_m014:newrel_f65,
names_to = "key",
values_to = "cases",
values_drop_na = TRUE
) %>%
# mutate(
# key = stringr::str_replace(key, "newrel", "new_rel")
# ) %>%
separate(key, c("new", "var", "sexage")) %>%
# select(-new, -iso2, -iso3) %>%
separate(sexage, c("sex", "age"), sep = 1)
```
```{r}
# 3 iso2 and iso3
redundant <- who %>%
pivot_longer(
cols = new_sp_m014:newrel_f65,
names_to = "key",
values_to = "cases",
values_drop_na = TRUE
) %>%
mutate(
key = stringr::str_replace(key, "newrel", "new_rel")
) %>%
separate(key, c("new", "var", "sexage")) %>%
# select(-new, -iso2, -iso3) %>%
separate(sexage, c("sex", "age"), sep = 1)
(redundant) # this tibble has 76,046 observations
redundant_dropped <- who %>%
pivot_longer(
cols = new_sp_m014:newrel_f65,
names_to = "key",
values_to = "cases",
values_drop_na = TRUE
) %>%
mutate(
key = stringr::str_replace(key, "newrel", "new_rel")
) %>%
separate(key, c("new", "var", "sexage")) %>%
select(-new, -iso2, -iso3) %>%
separate(sexage, c("sex", "age"), sep = 1)
(redundant_dropped) # This contains the same number of observations: 76,046
# %>% pivot_wider(names_from = country, values_from = iso2)
```
```{r}
# 3 iso2 and iso3
# redundant %>% select(iso3)
(redundant)
# redundant %>% group_by(country, new) %>% summarise() %>% count()
```
```{r 3 redundant iso2}
# There each country contains only one iso2
# There are no countries with more than one iso2 or contain a missing value of iso2
(redundant %>% group_by(country, iso2) %>% summarise() %>% count() %>% filter(n != 1 | is.na(n)))
country_iso2 <- redundant %>% group_by(country, iso2) %>% summarise()
n_unique_iso2_per_country <- length(unique(country_iso2$iso2))
# The number of countries are equal to the number of unique iso2
if (length(country_iso2$country) == n_unique_iso2_per_country){
print("The number of countries are equal to the number of unique iso2")
}
# If the number of unique were less, there would be repeated values or missing values.
# Because the number of unique iso is equal to the number of countries and each country only has one value, then these values are redundant.
```
```{r 3 iso3}
# There each country contains only one iso3
# There are no countries with more than one iso3 or contain a missing value of iso3
(redundant %>% group_by(country, iso3) %>% summarise() %>% count() %>% filter(n != 1 | is.na(n)))
country_iso3 <- redundant %>% group_by(country, iso3) %>% summarise()
n_unique_iso3_per_country <- length(unique(country_iso3$iso3))
# The number of countries are equal to the number of unique iso3
if (length(country_iso3$country) == n_unique_iso3_per_country){
print("The number of countries are equal to the number of unique iso3")
}
# If the number of unique were less, there would be repeated values or missing values.
# Because the number of unique iso is equal to the number of countries and each country only has one value, then these values are redundant.
```
```{r redundant new example}
# There each country contains only one iso3
# There are no countries with more than one iso3 or contain a missing value of iso3
(redundant %>% group_by(country, new) %>% summarise() %>% count() %>% filter(n != 1 | is.na(n)))
country_new <- redundant %>% group_by(country, new) %>% summarise()
n_unique_new_per_country <- length(unique(country_new$new))
# The number of countries are equal to the number of unique iso3
if (length(country_new$country) == n_unique_new_per_country){
print("The number of countries are equal to the number of unique new")
} else if(n_unique_new_per_country == 1) {
print("There is only 1 unique entry for every country. This variable is redundant because it holds no unique value.")
} else {
print("unique values found")
print(length(country_new$country))
print(n_unique_new_per_country)
}
# If the number of unique were less, there would be repeated values or missing values.
# There is only 1 unique entry for every country. This variable is redundant because it holds no value.
```
```{r redundancy counterexample}
# There each country contains only one iso3
# There are no countries with more than one iso3 or contain a missing value of iso3
(redundant %>% group_by(country, year) %>% summarise() %>% count() %>% filter(n != 1 | is.na(n)))
country_year <- redundant %>% group_by(country, year) %>% summarise()
n_unique_year_per_country <- length(unique(country_year$year))
# The number of countries are equal to the number of unique iso3
if (length(country_year$country) == n_unique_year_per_country){
print("The number of countries are equal to the number of unique new")
} else if(n_unique_year_per_country == 1) {
print("There is only 1 unique entry for every country. This variable is redundant because it holds no unique value.")
} else {
print("unique values found")
print(length(country_year$country))
print(n_unique_year_per_country)
}
# If the number of unique were less, there would be repeated values or missing values.
```
```{r}
# Quesion 4
base_who_q4 <- who %>%
pivot_longer(
cols = new_sp_m014:newrel_f65,
names_to = "key",
values_to = "cases",
values_drop_na = TRUE
) %>%
mutate(
key = stringr::str_replace(key, "newrel", "new_rel")
) %>%
separate(key, c("new", "var", "sexage")) %>%
select(-new, -iso2, -iso3) %>%
separate(sexage, c("sex", "age"), sep = 1)
```
```{r}
head(base_who_q4)
(number_of_cases_per_country <- base_who_q4 %>% group_by(country, cases) %>% summarise() %>% summarise(cases_per_country = sum(cases)))
(number_of_cases_per_year <- base_who_q4 %>% group_by(year, cases) %>% summarise() %>% summarise(cases_per_year = sum(cases)))
(number_of_cases_per_sex <- base_who_q4 %>% group_by(sex, cases) %>% summarise() %>% summarise(cases_per_sex = sum(cases)))
(number_of_cases_per_sex <- base_who_q4 %>% group_by(sex, cases) %>% summarise() %>% summarise(cases_per_sex = sum(cases)))
```
```{r}
# Quesion 1
# I would need to combine tables airports, flights, and planes. I would need to gather the longitude and lattitude of the origin and destination from airports in order to calculate the trajectory of the plane on a world map. I would need the distance calculated by the distance from the origin to the destination to identify the lenght of the line. I would need to group origin and destination by tailnum in flights to identify which flight tailnum went to which origin and destination.
```
```{r}
# Quesion 2
# The relationship between weather and airports is origin
```
```{r}
# Quesion 3
# Weather would need to include a relation to destination from flights.
```
```{r}
# Quesion 4
# I would want the following values in the table: holiday, month, day, year, number_of_people. The primary key would be the year, month, day and the foreign key would be the year, month, day in flights.
```
#### Section 13.3 Keys
#### Section 13.3.1 Exercises
```{r Add a surogate key to flights}
surogate_key <- nycflights13::flights
surogate_key %>% mutate(surogate_key = row_number()) %>% select(surogate_key, everything())
```
```{r 2. Identify the keys in the following datasets}
if(!require("Lahman")) install.packages("Lahman")
if(!require("babynames")) install.packages("babynames")
if(!require("nasaweather")) install.packages("nasaweather")
if(!require("fueleconomy")) install.packages("fueleconomy")
if(!require("ggplot2")) install.packages("ggplot2")
```
```{r 2.1 Identify the keys in the following datasets}
length(unique(Lahman::Batting$teamID))
length(Lahman::Batting$teamID)
Lahman::Batting
babynames::babynames
nasaweather::atmos
fueleconomy::vehicles
ggplot2::diamonds
# I would suggest that playerID is key in the Lahman dataset. There is no primary key in the Lahman dataset.
# There is no primary key in the babynames dataset. I would use the row_number as a surrogate key.
# A combination of lattitude, longitude, year, & month the categories I would use to create a surrogate key. Row number would work as well.
# id is the key in fueleconomy vehicles.
# There is no primary key in the ggplot2::diamonds dataset. I would mutate the rows to allow for a rownumber for each observation to be used as a key.
```
```{r}
```
```{r}
batting <- Lahman::Batting
pitching <- Lahman::Pitching
fielding <- Lahman::Fielding
```
```{r}
batting %>% count(playerID)
```
```{r}
pitching %>% count(playerID)
```
```{r}
fielding %>% group_by(playerID) %>% summarise(n())
```
```{r}
# Batting and pitching have a one to one relationship on playerID where one playerID in pitching relates to one playerID in batting. The same is true with respect to batting and fielding.
```
## Section 13.4: Mutating Joins
```{r Mutating Joins}
flights2 <- flights %>%
select(year:day, hour, origin, dest, tailnum, carrier)
flights2
```
```{r}
# A mutating join is akin to a left join
# Left Join
flights2 %>%
select(-origin, -dest) %>%
left_join(airlines, by = "carrier")
# Mutating Join
flights2 %>%
select(-origin, -dest) %>%
mutate(name = airlines$name[match(carrier, airlines$carrier)])
```
```{r}
flights2 %>%
select(-origin, -dest) %>%
left_join(airlines, by = "carrier")
```
#### 13.4.1 Understanding Joins
```{r Understanding Joins}
x <- tribble(
~key, ~val_x,
1, "x1",
2, "x2",
3, "x3"
)
y <- tribble(
~key, ~val_y,
1, "y1",
2, "y2",
4, "y3"
)
```
#### Section 13.4.2 Inner Joins
```{r}
x %>% inner_join(y, by = "key")
# Inner joins drop observations that are unmatched.
```
#### 13.4.3 Outer Joins
```{r }
x %>% left_join(y, by = 'key')
x %>% right_join(y, by = 'key')
x %>% full_join(y, by = 'key')
```
#### 13.4.4 Duplicate keys
```{r}
x <- tribble(
~key, ~val_x,
1, "x1",
2, "x2",
2, "x3",
1, "x4"
)
y <- tribble(
~key, ~val_y,
1, "y1",
2, "y2"
)
left_join(x, y, by = 'key')
```
```{r}
x <- tribble(
~key, ~val_x,
1, "x1",
2, "x2",
2, "x3",
3, "x4"
)
y <- tribble(
~key, ~val_y,
1, "y1",
2, "y2",
2, "y3",
3, "y4"
)
left_join(x,y, by = "key")
```
#### Defining the key columns
```{r}
flights2 %>%
left_join(weather)
```
```{r}
flights2 %>%
left_join(airports, c("dest" = "faa"))
```
```{r}
flights2 %>%
left_join(airports, c("origin" = "faa"))
```
#### Section 13.4.6 Exercises
```{r 1. Compute the average delay by destination, then join on the airports data frame so you can show the spatial distribution of delays}
airports %>%
semi_join(flights, c("faa" = "dest")) %>%
ggplot(aes(lon, lat)) +
borders("state") +
geom_point() +
coord_quickmap()
```
```{r}
flights
```
```{r}
airports
```
```{r}