This repository has been archived by the owner on Oct 10, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
lecture_day1-intermediate.Rmd
578 lines (411 loc) · 13 KB
/
lecture_day1-intermediate.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
---
title: "R 'hadley' workshop"
author: "Aurélien Ginolhac"
date: "2^nd^ June 2016"
output:
ioslides_presentation:
css: style.css
logo: img/uni.png
smaller: yes
fig_width: 6
fig_height: 5
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, cache = TRUE)
```
# dplyr
## dplyr - intro
There's a cheatsheet!
```{r echo=FALSE, out.width='90%'}
knitr::include_graphics("http://lsru.github.io/r_workshop/img/dplyr_cheatsheet.png")
```
```{r}
with(mtcars, aggregate(mpg, list(cyl), mean))
library("dplyr") # library("dplyr", warn.conflicts = FALSE)
mtcars %>%
group_by(cyl) %>%
summarize(mean(mpg))
```
[source by Steve Simpson](http://data-steve.github.io/base-r-groupby-tapply-ave-by/)
## Web-based app to learn by practise
step-by-step tidying and manipulating data frames
https://exploratory.io/
## nycflights13
`flights` is a `tbl_df`
```{r}
library("dplyr", warn.conflicts = FALSE)
library("nycflights13")
flights
```
## glimpse
Use `glimpse` to show some values and types per column. Environment tab does it too
```{r}
glimpse(flights)
```
## filter: inspect subsets of data
How many flights flew to La Guardia, NY in 2013? Expecting none...
```{r}
flights %>%
filter(dest == "LGA")
```
base version equivalent (`subset` could also be used)
```{r}
flights[which(flights$dest == "LGA"), ]
```
## filter: multiple conditions AND (&)
How many flights flew to Madison in first week of January?
```{r}
# Comma separated conditions are combined with '&'
flights %>%
filter(dest == "MSN", month == 1, day <= 7)
```
## filter: multiple conditions OR
```{r, eval = FALSE}
flights %>%
filter(dest == "MSN" | dest == "ORD" | dest == "MDW")
```
For more complicated checks, prefer a set operation.
The following 2 are equivalent:
```{r, eval = FALSE}
flights %>%
filter(is.element(dest, c("MSN", "ORD", "MDW")))
```
```{r, eval = FALSE}
flights %>%
filter(dest %in% c("MSN", "ORD", "MDW"))
```
## arrange: sort columns
Perform a nested sorting of all flights in NYC:
1. By which airport they departed
2. year
3. month
4. day
```{r}
flights %>%
arrange(origin, year, month, day)
```
## arrange desc: reverses sorting
Find the longest delays for flights to Madison.
<!--Find the longest delayed flights to Madison.-->
<!-- This would mean to search for the longest flight whatever the delay...-->
```{r}
flights %>%
filter(dest == "MSN") %>%
arrange(desc(arr_delay)) %>%
select(arr_delay, everything()) # way to reorder arr_delay 1st column
```
##
Find the most delayed (in minutes) flight in 2013
```{r}
flights %>%
arrange(desc(arr_delay)) %>%
select(arr_delay, everything()) %>% head(3)
```
```{r}
1272 / 60
```
## select columns
```{r}
flights %>%
select(origin, year, month, day)
```
## select's helpers
`select` has many helper functions. See `?select`.
works with `tidyr` functions too
```{r}
flights %>%
select(origin, year:day, starts_with("dep"))
```
## negative selecting
We can drop columns by "negating" the name. Since helpers
give us column names, we can negate them too.
```{r}
flights %>%
select(-dest, -starts_with("arr"),
-ends_with("time"))
```
## Recap: Verbs for inspecting data
* convert to a `tbl_df`. Now in `[tibble](https://github.com/hadley/tibble)`
* `glimpse` - some of each column
* `filter` - subsetting
* `arrange` - sorting (`desc` to reverse the sort)
* `select` - picking (and omitting) columns
## rename
Rename columns with `rename(NewName = OldName)`. To keep the order
correct, read/remember the renaming `=` as "was".
```{r}
flights %>%
rename(y = year, m = month, d = day)
```
## mutate
- How much departure delay did the flight make up in the air?
- Note that new variables can be used right away
```{r}
flights %>%
mutate(
gain = arr_delay - dep_delay,
speed = (distance / air_time) * 60,
gain_per_hour = gain / (air_time / 60)) %>%
select(gain:gain_per_hour)
```
## Could the gain be explained by speed?
```{r, warning=FALSE, fig.height=3.5}
library("ggplot2")
flights %>%
mutate(gain = arr_delay - dep_delay,
speed = (distance / air_time) * 60) %>%
sample_n(10000) %>% # subsample 1e5 rows randomly
ggplot(aes(x = gain, y = speed))+
geom_point(alpha = 0.4)
```
## group_by
For the flights to Madison, let's compute the average delay per month.
instead of `aggregate`, `dplyr` has its own grouping function.
Here, we `group_by` date. See the helpful reminder from `tbl_df` print method
```{r}
flights %>%
filter(dest == "MSN") %>%
group_by(month) %>%
#Some values are missing, thus tell `mean` to remove them from the calculation.
summarise(mean_dep_delay = mean(dep_delay, na.rm = TRUE))
```
## group_by (2)
Work per day, note the tibble info about the 365 groupings
```{r}
by_day <- flights %>%
group_by(year, month, day)
by_day
```
Note that one level (right most) is removed from grouping.
## summarise
Now we use `summarise` to compute (several) aggregate values within
each group (per day). `summarise` returns one row per group.
```{r}
by_day %>%
summarise(
flights = n(), # dplyr specific function
avg_delay = mean(dep_delay, na.rm = TRUE),
n_planes = n_distinct(tailnum)) # dplyr specific function
```
## Exercice
* In average, how many flights does a single plane perform each day?
* plot the distribution, display the mean / median (`geom_vline()`)
* plot the average delay per day. Use `tidyr:unite` and `as.Date`
* which day should be avoided?
## Solution 1
```{r}
by_day %>%
summarise(flights = n(),
avg_delay = mean(dep_delay, na.rm = TRUE),
n_planes = n_distinct(tailnum)) %>%
mutate(avg_flights = flights / n_planes)
```
## Solution 2
```{r, fig.align = 'center', out.width='100%', fig.height=3.1}
by_day %>%
summarise(flights = n(),
avg_delay = mean(dep_delay, na.rm = TRUE),
n_planes = n_distinct(tailnum)) %>%
mutate(avg_flights = flights / n_planes) %>%
ggplot()+
geom_density(aes(x = avg_flights))+
geom_vline(aes(xintercept = mean(avg_flights)), colour = "red")+
geom_vline(aes(xintercept = median(avg_flights)), colour = "blue")
```
## Solution 3
```{r, fig.align = 'center', out.width='100%', fig.height=3.3, warning = FALSE}
library("tidyr")
by_day %>%
summarise(avg_delay = mean(dep_delay, na.rm = TRUE)) %>%
ungroup() %>%
unite(date, -avg_delay, sep = "-") %>%
mutate(date = as.Date(date)) %>%
ggplot()+geom_bar(aes(x = date, y = avg_delay), stat = "identity")
```
## Solution 3
```{r, fig.align = 'center', out.width='80%', fig.height=3.5}
by_day %>%
summarise(avg_delay = mean(dep_delay, na.rm = TRUE)) %>%
arrange(desc(avg_delay))
```
What's wrong?
## Solution 3.2
Mind that `arrange` uses grouping! (will change in version `0.4.5`)
```{r, fig.align = 'center', out.width='100%'}
by_day %>%
summarise(avg_delay = mean(dep_delay, na.rm = TRUE)) %>%
ungroup %>%
arrange(desc(avg_delay))
```
## Exercice
* Find the destinations with the highest average arrival delay?
- discard flights with missing arrival delays
- count the number of flights per destination
- discard results with less than 10 flights: mean will not be meaningful
## Solution
```{r}
flights %>%
filter(!is.na(arr_delay)) %>%
group_by(dest) %>%
summarise(mean = mean(arr_delay),
n = n()) %>%
filter(n > 10) %>%
arrange(desc(mean))
```
## Is there a spatial pattern for those delays?
First get the GPS coordinate of airports using the data frame `airports`
```{r}
airports
```
## join two data frames
```{r}
delays <- flights %>%
filter(!is.na(arr_delay)) %>%
group_by(dest) %>%
summarise(mean = mean(arr_delay),
n = n()) %>%
filter(n > 10) %>%
arrange(desc(mean)) %>%
inner_join(airports, by = c("dest" = "faa")) # provide the equivalence since columns have a different name
```
We could have used **left_join** but 4 rows with a 3-letters acronym have no correspondance in the `airports` data frame.
**inner_join** narrows down the lines that are present in both data frames.
## join types
```{r, echo=FALSE, out.width='60%'}
knitr::include_graphics("http://www.dofactory.com/Images/sql-joins.png")
```
Of note: **anti_join** can select rows in which identifiers are **absent** in the second data frame.
## plot on a map
```{r, echo=TRUE, eval=FALSE, out.width='100%'}
library("ggplot2")
library("maps") # US map
ggplot(delays)+
geom_point(aes(x = lon, y = lat, colour = mean), size = 3, alpha = 0.8)+
scale_color_gradient2()+borders("state")
```
```{r, echo=FALSE, out.width='70%'}
knitr::include_graphics("img/delays_usmap_grey.png")
```
## plot on a map, with text
<!-- I'm not able to set warning or message to FALSE! -->
<!-- Index out of range error for map_data... -->
```{r, eval=FALSE, message = TRUE, warning = TRUE, out.width='100%'}
library("ggrepel")
filter(delays, lon > -140) %>% # remove Honolulu
ggplot()+geom_point(aes(x = lon, y = lat, colour = mean), size = 3, alpha = 0.8)+
geom_text_repel(aes(x = lon, y = lat, label = name), size = 2.5)+
scale_color_gradient2()+theme_classic()+borders("state")
```
```{r, echo=FALSE, out.width='70%'}
knitr::include_graphics("img/delays_usmap.png")
```
## plot on a map, with conditional text
```{r, out.width='100%', eval=FALSE}
filter(delays, lon > -140) %>% # remove Honolulu
ggplot()+geom_point(aes(x = lon, y = lat, colour = mean),
size = 3, alpha = 0.8)+borders("state")+
geom_label_repel(data = delays %>% filter(mean > 20),
aes(x = lon, y = lat + 1, label = name), fill = "brown", colour = "white", size = 3)+
scale_color_gradient2()+theme_classic()
```
```{r, echo=FALSE, out.width='70%'}
knitr::include_graphics("img/delays_cond_usmap.png")
```
## tally / count
`tally` is a shortcut to counting the number of items per group.
```{r}
flights %>%
group_by(dest, month) %>%
tally() %>% head(3) # could sum up with multiple tally calls
```
`count` does the grouping for you
```{r}
flights %>%
count(dest, month) %>% head(3)
```
## That covers 80% of dplyr
- select
- filter
- arrange
- glimpse
- rename
- mutate
- group_by, ungroup
- summarise
## Other 20%
- assembly: `bind_rows`, `bind_cols`
- windows function, `min_rank`, `dense_rank`, `cumsum`
- column-wise operations: `mutate_each`, `transmute`, `summarise_each`
- join tables together: `right_join`, `full_join`
- filtering joins: `semi_join`, `anti_join`
- `do`: arbitrary code on each chunk
- different types of tabular data (databases, data.tables)
## bind_rows + purrr
How to read in and merge files in 2 lines
```{r}
library("purrr")
library("readxl")
files <- list.files(path = "./data/", pattern = "xlsx$", full.names = TRUE)
df <- lapply(files, read_excel) %>% bind_rows(.id = "file_number")
```
using `purrr`
```{r}
purr_df <- map_df(files, read_excel, .id = "file_number")
```
filenames are better
```{r}
library("stringr")
files %>%
set_names(nm = str_match(basename(.), "([^.]+)\\.[[:alnum:]]+$")[, 2]) %>%
map_df(read_excel, .id = "file_name") -> purr_name_df
```
# Appendix
## Coding style
`R` has a rather flexible and permissive syntax. However, being more strict tends to ease the debugging process.
See [Hadley's recommendations](http://adv-r.had.co.nz/Style.html)
```{r, eval=FALSE}
long_function_name <- function(a = "a long argument",
b = "another argument",
c = "another long argument") {
# As usual code is indented by two spaces.
}
```
## Useful rstudio shortcuts
- Scripting (replace <kbd>Cmd</kbd> by <kbd>Ctrl</kbd> for PC)
+ <kbd>Cmd</kbd> + <kbd>-</kbd>: insert <kbd> <- </kbd>
+ <kbd>Cmd</kbd> + <kbd>Shift</kbd> + <kbd>M</kbd>: insert <kbd>%>%</kbd>
+ <kbd>Alt</kbd> + <kbd>↑</kbd> or <kbd>↓</kbd>: move line up / down
+ <kbd>Cmd</kbd> + <kbd>Alt</kbd> + <kbd>↑</kbd> or <kbd>↓</kbd>: copy line up / down
+ <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>↑</kbd> or <kbd>↓</kbd>: multi-line edition
- `# analysis step ####` for navigating
- Running
+ <kbd>Cmd</kbd> + <kbd>Enter</kbd>: run code
+ <kbd>Cmd</kbd> + <kbd>Shift</kbd> + <kbd>P</kbd>: re-run Previous code
+ <kbd>Cmd</kbd> + <kbd>Shift</kbd> + <kbd>K</kbd>: Knit document
## Rstudio addins
[Addins](https://rstudio.github.io/rstudioaddins/) are small integrated packages that solve small tasks.
```{r, echo = FALSE, out.width='60%'}
knitr::include_graphics("img/rstudio_addins.png")
```
[Dean Attali](deanattali.com/) created a [package](https://github.com/daattali/addinslist#readme) to explore and manage your addins.
Sometimes, cause crashes
## Recommended reading
- [R for data science](http://r4ds.had.co.nz/)
```{r, echo = FALSE, out.width='10%'}
knitr::include_graphics("https://raw.githubusercontent.com/hadley/r4ds/master/cover.png")
```
- [Advanced in R](http://adv-r.had.co.nz/) by Hadley
- About R weirdness
+ [R inferno](http://www.burns-stat.com/documents/books/the-r-inferno/) by Patrick Burns
+ [Rbitrary](https://ironholds.org/projects/rbitrary/) by Oliver Keyes
See why:
- `<-` and not `=`
- `::` and not `:::`
- `library` and not `require` etc.
## Acknowledgments
* Hadley Wickham
* Steve Simpson
* Jenny Bryan
* Dean Attali
* David Robinson
* Eric Koncina