forked from Jing907/RLadies
-
Notifications
You must be signed in to change notification settings - Fork 2
/
20180110_Purrr_Workshop.Rmd
451 lines (257 loc) · 5.93 KB
/
20180110_Purrr_Workshop.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
---
title: "Purrr Tutorial"
author: "Joyce Robbins"
output: slidy_presentation
editor_options:
chunk_output_type: inline
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, message = FALSE,
warning = FALSE)
```
# Purrr Tutorial
January 10, 2018
Joyce Robbins
[email protected] Twitter: @jtrnyc
this file: https://github.com/jtr13/RLadies/blob/master/20180110_Purrr_Workshop.Rmd
# Agenda
### 1. Why purrr?
(or apply functions)
* Saves you work (= time)
* Cleaner code
### 2. <strike>Review of fundamentals</strike>
Mindfulness/Vigilance of
* data types: integer, double, logical, character, factor
* data structures: vector, data frame / tibble, list (, matrix, array)
... in the context of functions
### 3. Data frames
* do something to a column
* do it to every column
### 4. Simple (unnested) lists
* get the information that you need from each element
* combine multiple pieces of information into a data frame
### 5. Nested lists
# R you ready?
```{r ready}
knitr::include_graphics("wecandoit.jpg")
```
# Data structures
### vector
```{r vector1}
x <- c(3, 4, 5)
x
```
### data frame / tibble
```{r tibble1}
tib <- tibble(a = c(1, 2), b = c(3, 4), c = c("cat", "dog"))
tib
```
```{r dataframe1}
df <- data.frame(a = c(1, 2), b = c(3, 4), c = c("cat", "dog"))
df
```
### list
```{r list1}
x <- list(a = c(first = 1, second = 2),
b = c(TRUE, FALSE, TRUE),
c = c("cat", "dog", "fish", "elephant"))
```
What does the data structure look like?
--> You need to know what you have
My 3 go-tos:
* x
* str(x)
* Object Explorer a.k.a. View(x)
```{r x}
x
```
str()
```{r str1}
knitr::include_graphics("stiritup.png")
```
```{r strx}
str(x)
```
Object Explorer
```{r another example}
xvar <- rnorm(10)
yvar <- xvar + rnorm(10)
mod <- lm(yvar ~ xvar)
# Go to Object Explorer
```
# Simple functions
```{r simple}
x <- 1:10
x
```
What's the input? What's the output?
```{r min1}
min(x)
```
What's the input? What's the output?
```{r mean1}
mean(x)
```
What's the input? What's the output?
```{r length1}
length(x)
```
# More simple functions
What's going on now?
```{r sqrt1}
sqrt(x)
```
```{r round1}
round(x + .5)
```
```{r round2}
y <- x/10 + 1.05
y
round(y, 1)
```
Now we're ready for map (or lapply) to do the same thing to each column of a data frame.
# Data frames
```{r dataframe1}
df <- data.frame(
x = c(3, 4, 5, 6),
y = c(7, 8, 9, 10),
z = c(11, 12, 13, 14))
df
```
How do we take the mean of each column?
```{r forloop1}
# Don't do this:
for (i in 1:3) print(mean(df[,i]))
```
```{r lapply1}
# Do this:
lapply(df, mean)
```
```{r map1}
library(tidyverse)
# Or this:
map(df, mean)
```
Find the mean snowfall by day (that is, find the mean for each column separately)
Problem: lots of NAs
snow.csv: February 2017, New York State, daily by collecting station (349)
```{r snow}
snow <- read_csv("snow.csv")
dim(snow)
View(snow)
```
```{r snowtotals}
snowmean <- function(x) mean(na.omit(x))
# test it
snowmean(c(NA, 3, 5))
dailymeans <- map(snow, snowmean)
dailymeans[1:3]
```
Use an anonymous function to do the same thing:
```{r before}
# from before:
snowsum <- function(x) sum(na.omit(x))
total <- map(snow, snowsum)
```
# Version 1: replace function name with function contents
```{r version1}
total <- map(snow, function(x) sum(na.omit(x)))
total[1:3]
```
# Version 2: replace "x" with ".x" (it's just another variable name)
```{r}
total <- map(snow, function(.x) sum(na.omit(.x)))
total[1:3]
```
# Version 3: replace "function(.x)" with "~" (you must use .x if you do this)
```{r}
total <- map(snow, ~sum(na.omit(.x)))
```
-> If you don't like this notation, stick with named functions!
-> One more thing: we can use typed functions
```{r}
total <- map_dbl(snow, ~sum(na.omit(.x)))
total
```
-> map returns a LIST of double, map_dbl returns a VECTOR of double
-> map_lgl, map_int, map_chr all return VECTORS of type ...
RECAP
-> We can do the same thing to every column of a data frame
-> Get the function the work on one vector before you try it on the whole data frame
# Lists
```{r}
x <- list(a = c(first = 1, second = 2),
b = c(TRUE, FALSE, TRUE),
c = c("cat", "dog", "fish", "elephant"))
```
Get the first item in each list:
```{r}
map(x, 1)
```
Get the second item:
```{r}
map(x, 2)
```
Get the third item:
```{r}
map(x, 3)
```
Get the last item:
```{r}
map(x, tail, 1)
```
```{r}
lapply(x, tail, 1)
```
Get the named items from a list:
```{r}
organizers <- list(
list(firstname = "Soumya", lastname = "Kalra"),
list(firstname = "Brooke", lastname = "Watson"),
list(firstname = "Emily", lastname = "Zabor"),
list(firstname = "Gabriela", lastname = "Hempfling"),
list(firstname = "Emily", lastname = "Robinson"),
list(firstname = "Jasmine", lastname = "Williams"),
list(firstname = "Birunda", lastname = "Chelliah"))
```
```{r}
map(organizers, "firstname")
```
```{r}
map_chr(organizers, "firstname")
```
Create a data frame from a list:
```{r}
map(organizers, `[`, "firstname")
```
```{r}
map_df(organizers, `[`, c("firstname", "lastname"))
```
-> Only works if each column has the same number of elements
(Watch out for map_df... you may get great results or a colossal fail)
# Nested lists
```{r}
library(jsonlite)
nobel <- fromJSON("http://api.nobelprize.org/v1/prize.json")
View(nobel)
```
```{r}
year <- nobel$prizes$year
category <- nobel$prizes$category
laureates <- nobel$prizes$laureates
View(laureates)
```
What is the total number of people who have won nobel prizes (don't count organizations)?
```{r}
winners <- map(laureates, "surname")
removeblank <- function(x) {
x[x != ""]
}
winners <- map(winners, removeblank) %>% compact()
mean(map_int(winners, ~length(.x))
```
For more practice:
Jenny Bryan "repurrrsive" package
https://github.com/jdorfman/awesome-json-datasets
Joyce Robbins
[email protected] @jtrnyc