-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path5-good-code.html
More file actions
358 lines (272 loc) · 10.1 KB
/
5-good-code.html
File metadata and controls
358 lines (272 loc) · 10.1 KB
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
<!DOCTYPE html>
<html>
<head>
<title>Reproducable scripts</title>
<meta charset="utf-8">
<meta name="author" content="Devin Judge-Lord" />
<link rel="stylesheet" href="templates/xaringan-themer.css" type="text/css" />
</head>
<body>
<textarea id="source">
class: center, middle, inverse, title-slide
# Reproducable scripts
### Devin Judge-Lord
---
# Be nice to others

---
# Be nice to yourself

---
class: center inverse
## How to break a research project

---
## 1. `setwd("user\path\only\I\have")`
--

### We don't have your file paths!
You won't have those file paths on your next computer, a lab computer, a remote server.
---
## 2. [Factors](https://www.r-bloggers.com/factors-are-not-first-class-citizens-in-r/)
```r
strings <- c("a","a","b",NA,"c","c")
f <- factor(strings)
f
```
```
## [1] a a b <NA> c c
## Levels: a b c
```
```r
ifelse(is.na(f),'b',f)
```
```
## [1] "1" "1" "2" "b" "3" "3"
```
### If working with text, begin with: `options(stringsAsFactors = F)`
Let R coerce strings to factors as needed.
Eventually, learn to master factors with [`forcats`](https://forcats.tidyverse.org/) (e.g., if you want to plot things in a specific order.)
---
## 3.
### `library(SomoneoneOnTheInternetWroteThis)`
--

### I may not have your packages!
---
## Tip: A seperate script to set it all up
### `source("setup.R")`
```
options(stringsAsFactors = F)
## Add any R packages you require.
## Here are some we will use in 811:
requires <- c("tidyverse", # tidyverse includes dplyr and ggplot2
"magrittr",
"here")
## Install any you don't have
to_install <- c(requires %in% rownames(installed.packages()) == FALSE)
install.packages(c(requires[to_install], "NA"), repos = "https://cloud.r-project.org/" )
```
```
## Load all required R packages
library(tidyverse)
library(ggplot2); theme_set(theme_bw()) ## Set global ggplot theme
library(magrittr)
library(here)
```
---
### `source("setup.R")` continued:
```
## Set defaults for R chunks
knitr::opts_chunk$set(echo = TRUE, # echo = TRUE means that your code will show
warning=FALSE,
message=FALSE,
fig.retina = 2,
fig.align = "center",
dpi = 100,
# fig.path='Figs/', ## where to save figures
fig.height = 3,
fig.width = 3)
```
---
## 4. `data[2:7,]`: always the same observations?
--
## Use `filter()`
Subset to rows (observations!) matching certain conditions

---
## 5. `data[, 2:7]`: always the same variables?
--
## Use `select()`
Select columns (variables!) or column names matching certain conditions
---
### What is the UN up to?
```r
html <- read_html("https://www.UN.org/") # The UN homepage
links <- html_nodes(html, "a") # "a" nodes are linked text
tibble(text = html_text(links),
url = html_attr(links, "href") ) %>% # "href"" attributes are urls
filter(str_detect(url, "events")) %>% # urls containing "events"
select(text) %>% # or select(-url)
distinct()
```
```
## # A tibble: 6 x 1
## text
## <chr>
## 1 "اليوم الدولي للتوعية بخطر الألغام\r\n\r\n4 نيسان/أبريل\r\n"
## 2 国际提高地雷意识和协助地雷行动日-4月4日
## 3 International Mine Awareness Day - 4 April
## 4 Journée internationale pour la sensibilisation au problème des mines et …
## 5 Международный день просвещения по вопросам минной опасности и помощи в д…
## 6 Día Internacional de información sobre el peligro de las minas y de asis…
```
---
### To do something more than once, use [functions](https://r4ds.had.co.nz/functions.html#functions).
```r
top_story <- function(x){
html <- read_html(str_c("https://www.UN.org/", x)) # The UN homepage
links <- html_nodes(html, "a") # "a" nodes are linked text
d <- tibble(text = html_text(links),
url = html_attr(links, "href") # href attributes are urls
) %>%
filter(text != "", str_detect(url, "/story")) %>% # urls that contain "story"
.[1,]
return(d)
}
```
```r
top_story(x = "en")
```
```
## # A tibble: 1 x 2
## text url
## <chr> <chr>
## 1 ‘The welfare of the Libyan people’ the UN’s … https://news.un.org/en/sto…
```
```r
top_story(x = "ru")
```
```
## # A tibble: 1 x 2
## text url
## <chr> <chr>
## 1 "Генсек ООН покинул Ливию «с тяжелым … https://news.un.org/ru/story/2019…
```
---
## Apply functions with [`purrr`](https://www.rstudio.com/resources/cheatsheets/#purrr)
(Instead of writing loops where we have to index everything.)
```r
languages <- c("ar", "zh", "en", "fr", "ru", "es")
map_dfr(languages, top_story)
```
```
## # A tibble: 6 x 2
## text url
## <chr> <chr>
## 1 غوتيريش: طفرة في العمل الدبلوماسي لحل الصراع… https://news.un.org/ar/sto…
## 2 利比亚国民军向首都挺进 联合国秘书长呼吁避免“血腥对抗”… https://news.un.org/zh/sto…
## 3 ‘The welfare of the Libyan people’ the UN’s … https://news.un.org/en/sto…
## 4 En visite en Libye, le chef de l’ONU se dit … https://news.un.org/fr/sto…
## 5 "Генсек ООН покинул Ливию «с тяжелым сердцем… https://news.un.org/ru/sto…
## 6 Guterres reitera el compromiso de la ONU de … https://news.un.org/es/sto…
```
---
## Simpler is often stronger.

--
- Use `%>%` and `%<>%` instead of making a million objects
- Use `map()` and other `purrr` functions instead of loops
---
## Computing
Have long scripts [send you a text or email](https://github.com/jennybc/send-email-with-r) when they are done with a task.
Spread computation across several cores with [`multidplyr`](https://github.com/hadley/multidplyr/blob/master/vignettes/multidplyr.md)
Use a remote, like [SSCC's linstat cluster](https://www.ssc.wisc.edu/sscc/pubs/linstat.htm)
- Easy to `git clone` if you have a self-contained project folder on git
</textarea>
<style data-target="print-only">.remark-slide-container{display:block;}.remark-slide-scaler{box-shadow:none;}</style>
<script src="https://remarkjs.com/downloads/remark-latest.min.js"></script>
<script>var slideshow = remark.create({
"highlightStyle": "github",
"highlightLines": true,
"countIncrementalSlides": false
});
if (window.HTMLWidgets) slideshow.on('afterShowSlide', function (slide) {
window.dispatchEvent(new Event('resize'));
});
(function(d) {
var s = d.createElement("style"), r = d.querySelector(".remark-slide-scaler");
if (!r) return;
s.type = "text/css"; s.innerHTML = "@page {size: " + r.style.width + " " + r.style.height +"; }";
d.head.appendChild(s);
})(document);
(function(d) {
var el = d.getElementsByClassName("remark-slides-area");
if (!el) return;
var slide, slides = slideshow.getSlides(), els = el[0].children;
for (var i = 1; i < slides.length; i++) {
slide = slides[i];
if (slide.properties.continued === "true" || slide.properties.count === "false") {
els[i - 1].className += ' has-continuation';
}
}
var s = d.createElement("style");
s.type = "text/css"; s.innerHTML = "@media print { .has-continuation { display: none; } }";
d.head.appendChild(s);
})(document);
// delete the temporary CSS (for displaying all slides initially) when the user
// starts to view slides
(function() {
var deleted = false;
slideshow.on('beforeShowSlide', function(slide) {
if (deleted) return;
var sheets = document.styleSheets, node;
for (var i = 0; i < sheets.length; i++) {
node = sheets[i].ownerNode;
if (node.dataset["target"] !== "print-only") continue;
node.parentNode.removeChild(node);
}
deleted = true;
});
})();</script>
<script>
(function() {
var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
if (/^(https?:)?\/\//.test(links[i].getAttribute('href'))) {
links[i].target = '_blank';
}
}
})();
</script>
<script>
(function() {
var i, text, code, codes = document.getElementsByTagName('code');
for (i = 0; i < codes.length;) {
code = codes[i];
if (code.parentNode.tagName !== 'PRE' && code.childElementCount === 0) {
text = code.textContent;
if (/^\\\((.|\s)+\\\)$/.test(text) || /^\\\[(.|\s)+\\\]$/.test(text) ||
/^\$\$(.|\s)+\$\$$/.test(text) ||
/^\\begin\{([^}]+)\}(.|\s)+\\end\{[^}]+\}$/.test(text)) {
code.outerHTML = code.innerHTML; // remove <code></code>
continue;
}
}
i++;
}
})();
</script>
<!-- dynamically load mathjax for compatibility with self-contained -->
<script>
(function () {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://cdn.bootcss.com/mathjax/2.7.1/MathJax.js?config=TeX-AMS_HTML';
if (location.protocol !== 'file:' && /^https?:/.test(script.src))
script.src = script.src.replace(/^https?:/, '');
document.getElementsByTagName('head')[0].appendChild(script);
})();
</script>
</body>
</html>