-
Notifications
You must be signed in to change notification settings - Fork 1
/
lessons_programming_in_R.html
576 lines (515 loc) · 20.3 KB
/
lessons_programming_in_R.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
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="pandoc" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Programming in R</title>
<script src="libs/jquery-1.11.3/jquery.min.js"></script>
<script src="libs/jqueryui-1.11.4/jquery-ui.min.js"></script>
<link href="libs/tocify-1.9.1/jquery.tocify.css" rel="stylesheet" />
<script src="libs/tocify-1.9.1/jquery.tocify.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="libs/bootstrap-3.3.5/css/flatly.min.css" rel="stylesheet" />
<script src="libs/bootstrap-3.3.5/js/bootstrap.min.js"></script>
<script src="libs/bootstrap-3.3.5/shim/html5shiv.min.js"></script>
<script src="libs/bootstrap-3.3.5/shim/respond.min.js"></script>
<link rel="stylesheet" href="libs/font-awesome-4.1.0/css/font-awesome.min.css"/>
<link rel="stylesheet" href="pols503.css"/>
<style type="text/css">code{white-space: pre;}</style>
<link rel="stylesheet"
href="libs/highlight/textmate.css"
type="text/css" />
<script src="libs/highlight/highlight.js"></script>
<style type="text/css">
pre:not([class]) {
background-color: white;
}
</style>
<script type="text/javascript">
if (window.hljs && document.readyState && document.readyState === "complete") {
window.setTimeout(function() {
hljs.initHighlighting();
}, 0);
}
</script>
</head>
<body>
<style type = "text/css">
.main-container {
max-width: 940px;
margin-left: auto;
margin-right: auto;
}
code {
color: inherit;
background-color: rgba(0, 0, 0, 0.04);
}
img {
max-width:100%;
height: auto;
}
h1 {
font-size: 34px;
}
h1.title {
font-size: 38px;
}
h2 {
font-size: 30px;
}
h3 {
font-size: 24px;
}
h4 {
font-size: 18px;
}
h5 {
font-size: 16px;
}
h6 {
font-size: 12px;
}
.tabbed-pane {
padding-top: 12px;
}
button.code-folding-btn:focus {
outline: none;
}
</style>
<style type="text/css">
/* padding for bootstrap navbar */
body {
padding-top: 60px;
padding-bottom: 40px;
}
/* offset scroll position for anchor links (for fixed navbar) */
.section h1 {
padding-top: 65px;
margin-top: -65px;
}
.section h2 {
padding-top: 65px;
margin-top: -65px;
}
.section h3 {
padding-top: 65px;
margin-top: -65px;
}
.section h4 {
padding-top: 65px;
margin-top: -65px;
}
.section h5 {
padding-top: 65px;
margin-top: -65px;
}
.section h6 {
padding-top: 65px;
margin-top: -65px;
}
</style>
<script>
// manage active state of menu based on current page
$(document).ready(function () {
// active menu anchor
href = window.location.pathname
href = href.substr(href.lastIndexOf('/') + 1)
if (href === "")
href = "index.html";
var menuAnchor = $('a[href="' + href + '"]');
// mark it active
menuAnchor.parent().addClass('active');
// if it's got a parent navbar menu mark it active as well
menuAnchor.closest('li.dropdown').addClass('active');
});
</script>
<div class="container-fluid main-container">
<!-- tabsets -->
<script src="libs/navigation-1.0/tabsets.js"></script>
<script>
$(document).ready(function () {
window.buildTabsets("TOC");
});
</script>
<!-- code folding -->
<script>
$(document).ready(function () {
// establish options
var options = {
selectors: "h1,h2",
theme: "bootstrap3",
context: '.toc-content',
hashGenerator: function (text) {
return text.replace(/[.\/?&!#<>]/g, '').replace(/\s/g, '_').toLowerCase();
},
ignoreSelector: "h1.title, .toc-ignore",
scrollTo: 0
};
options.showAndHide = true;
options.smoothScroll = true;
// tocify
var toc = $("#TOC").tocify(options).data("toc-tocify");
});
</script>
<style type="text/css">
#TOC {
margin: 25px 0px 20px 0px;
}
@media (max-width: 768px) {
#TOC {
position: relative;
width: 100%;
}
}
.toc-content {
padding-left: 30px;
padding-right: 40px;
}
div.main-container {
max-width: 1200px;
}
div.tocify {
width: 20%;
max-width: 260px;
max-height: 85%;
}
@media (min-width: 768px) and (max-width: 991px) {
div.tocify {
width: 25%;
}
}
@media (max-width: 767px) {
div.tocify {
width: 100%;
max-width: none;
}
}
.tocify ul, .tocify li {
line-height: 20px;
}
.tocify-subheader .tocify-item {
font-size: 0.9em;
padding-left: 5px;
}
.tocify .list-group-item {
border-radius: 0px;
}
</style>
<!-- setup 3col/9col grid for toc_float and main content -->
<div class="row-fluid">
<div class="col-xs-12 col-sm-4 col-md-3">
<div id="TOC" class="tocify">
</div>
</div>
<div class="toc-content col-xs-12 col-sm-8 col-md-9">
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button"
class="navbar-toggle collapsed"
data-toggle="collapse"
data-target="#navbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="https://UW-POLS503.github.io/pols_503_sp16">POLS/CS&SS 503</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a href="index.html">Home</a></li>
<li><a href="schedule.html">Schedule</a></li>
<li><a href="https://uw-pols503.github.io/pols503-notes/">Notes</a></li>
<!-- start assignments dropdown -->
<li class="dropdown">
<a href="assignments" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Assignments <span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<!-- ADD NEW ASSIGNMENTS HERE -->
<li class="dropdown-header">Assignments</li>
<li><a href="https://github.com/UW-POLS503/Assignment_01">Assignment 1</a></li>
<li class="divider"></li>
<li class="dropdown-header">Project</li>
<li><a href="assignments_project_1.html">Project Assignment 1</a></li>
<li><a href="assignments_project_2.html">Project Assignment 2</a></li>
<li><a href="assignments_project_3.html">Project Assignment 3</a></li>
<li><a href="data_analysis_project_paper_guidelines.html">Final Project</a></li>
<li class="divider"></li>
<li class="dropdown-header">Peer Review</li>
<li><a href="assignments_peer_review_1.html">Peer Review 1</a></li>
<li><a href="assignments_peer_review_2.html">Peer Review 2</a></li>
</ul>
</li>
<!-- end assignments dropdown -->
<!-- start lessons dropdown -->
<li class="dropdown">
<a href="lessons" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Lessons <span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<!-- ADD NEW LESSONS HERE -->
<li><a href="lessons_install_R.html">Installing R</a></li>
<li><a href="lessons_git.html">Getting Started with Git and GitHub</a></li>
<li><a href="lessons_writing_functions.html">Writing Functions</a></li>
<li><a href="lessons_loops_conditionals.html">Loops and Conditional Execution</a></li>
<li><a href="lessons_functional_forms2.html">Functional Forms</a></li>
<li><a href="lessons_imputation.html">Multiple Imputation</a></li>
<li><a href="lessons_weights.html">Weights</a></li>
</ul>
</li>
<!-- end lessons dropdown -->
<!-- start references dropdown -->
<li class="dropdown">
<a href="references" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">References <span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<!-- ADD NEW REFERENCE PAGES HERE -->
<li><a href="writing-advice.html">Writing Advice</a></li>
<li><a href="latex4research.html">LaTeX</a></li>
<li><a href="word4research.html">Word for Research</a></li>
<li><a href="Rmarkdown.html">R Markdown</a></li>
<li><a href="stata_to_R.html">Moving from Stata to R</a></li>
<li><a href="submitting-assign.html"> Submitting Assignments</a></li>
</ul>
</li>
<!-- end references dropdown -->
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="https://github.com/UW-POLS503/pols_503_sp16/issues">Report Bug</a></li>
</ul>
</div><!--/.nav-collapse -->
</div><!--/.container -->
</div><!--/.navbar -->
<div class="fluid-row" id="header">
<h1 class="title">Programming in R</h1>
</div>
<div id="learning-objectives" class="section level2">
<h2>Learning Objectives</h2>
<ul>
<li>You will learn some basic R programming to make code less redundant and more efficient</li>
<li>You will learn how to write and use R functions</li>
<li>You will learn how to write and use <code>for</code> loops</li>
<li>You will learn how to write and use conditional execution (<code>if</code>-<code>else</code> statements)</li>
</ul>
</div>
<div id="required-packages-and-datasets" class="section level2">
<h2>Required Packages and Datasets</h2>
<p>Make sure you can load all these packages and dataset before starting the module</p>
<pre class="r"><code>library(dplyr)
library(uwpols501)
data(turnout)</code></pre>
</div>
<div id="functions" class="section level2">
<h2>Functions</h2>
<p>Why should we use functions? Well, don’t take it from me, take it from <a href="http://r4ds.had.co.nz/functions.html">Grolemund & Wickham (2016)</a>:</p>
<p><em>Writing a function has three big advantages over using copy-and-paste:</em></p>
<ol style="list-style-type: decimal">
<li><em>You drastically reduce the chances of making incidental mistakes when you copy and paste.</em></li>
<li><em>As requirements change, you only need to update code in one place, instead of many.</em></li>
<li><em>You can give a function an evocative name that makes your code easier to understand.</em></li>
</ol>
<p>Writing a function step by step:</p>
<ol style="list-style-type: decimal">
<li>Specify a function name</li>
<li>Use the <code>function()</code> command</li>
<li>Specify inside the <code>function()</code> command the arguments that the functions takes</li>
<li>Write what the function does between the curly brackets <code>{ }</code> (Function names should be verbs, and arguments should be nouns)</li>
</ol>
<p>A function has the following skeleton:</p>
<pre class="r"><code>function_name <- function(argument1, argument2, ...) {
# do_something with the arguments
output <- argument1 + argument2
return(output)
}</code></pre>
<p>A short/silly example:</p>
<pre class="r"><code>say_hi <- function(name) {
full_statement <- paste0("Hi! My name is ", name)
return(full_statement)
}
full_statement <- say_hi("Andreu")
full_statement</code></pre>
<pre><code>## [1] "Hi! My name is Andreu"</code></pre>
<p>A real example:</p>
<p>For the final project last quarter, one of your classmates needed to retrieve the first digit of all numbers for several numeric variables. So the person had to write the same code multiple times. Let’s now write a function that would simplify that code.</p>
<pre class="r"><code>get_first_digit <- function(variable) {
num_digits <- nchar(variable)
var_first_num <- variable %/% (10 ^ (nchar(variable) - 1))
return(var_first_num)
}</code></pre>
<p>Now apply the function <code>get_first_digit()</code> that we just created to the variables <code>age</code> and <code>educate</code> of the <code>turnout</code> dataset.</p>
<pre class="r"><code>turnout$age_new <- get_first_digit(turnout$age)
turnout$educate_new <- get_first_digit(turnout$educate)</code></pre>
<div id="challenge-1" class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">
Challenge
</h3>
</div>
<div class="panel-body">
<p>Look through some of your previous code from other classes and projects, and write a function to reduce redundancy (10 min.)</p>
</div>
</div>
</div>
<div id="for-loops" class="section level2">
<h2>For Loops</h2>
<p>We use <code>for</code> loops to iterate through multiple elements of a list, variable, etc., and do <strong>something</strong> with those elements.</p>
<p>A <code>for</code> loop has the following skeleton:</p>
<pre class="r"><code>for (each_element in here) { # Try to use meaningful names for the
# do something # "each_element" object
print(each_element + 1)
}</code></pre>
<p>A short/silly example:</p>
<pre class="r"><code>list_numbers <- sample(x = 1:100, size = 10, replace = FALSE) # sample() function
for (number in list_numbers) {
print(paste0("2 times ", number, " is ", number * 2))
}</code></pre>
<pre><code>## [1] "2 times 26 is 52"
## [1] "2 times 55 is 110"
## [1] "2 times 6 is 12"
## [1] "2 times 46 is 92"
## [1] "2 times 47 is 94"
## [1] "2 times 78 is 156"
## [1] "2 times 35 is 70"
## [1] "2 times 51 is 102"
## [1] "2 times 16 is 32"
## [1] "2 times 57 is 114"</code></pre>
<p>A real example:</p>
<p>Going back to the <code>turnout</code> dataset. Imagine that we want to estimate the same linear model for different groups of people based on their age: if they’re in their 20s, 30s, etc. We can do that using a <code>for</code> loop and the <code>age_new</code> variable we just created. We want to estimate the following linear model:</p>
<pre class="r"><code>model_formula <- vote ~ educate + income</code></pre>
<p>We first create an empty <code>results</code> dataset that we’ll fill with the coefficients and SEs of each model run.</p>
<pre class="r"><code>groups <- sort(unique(turnout$age_new))
results <- data.frame(age_new = groups,
edu_coef = rep(NA, length(groups)),
edu_se = rep(NA, length(groups)),
inc_coef = rep(NA, length(groups)),
inc_se = rep(NA, length(groups)))</code></pre>
<p>Now we estimate the model for each age group and we store the coefficients and SEs for each covariate in the <code>results</code> dataset.</p>
<pre class="r"><code>for (i in 1:length(groups)) {
gr <- groups[i]
sub_data <- filter(turnout, age_new == gr)
gr_model <- lm(model_formula, data = sub_data)
results$edu_coef[i] <- coef(gr_model)[2]
results$edu_se[i] <- sqrt(diag(vcov(gr_model)))[2]
results$inc_coef[i] <- coef(gr_model)[3]
results$inc_se[i] <- sqrt(diag(vcov(gr_model)))[3]
}
results</code></pre>
<pre><code>## age_new edu_coef edu_se inc_coef inc_se
## 1 1 0.140059313 0.082778700 0.01274892 0.039715750
## 2 2 0.063378607 0.009439463 0.02507891 0.010440232
## 3 3 0.021207718 0.007576099 0.02046039 0.008160295
## 4 4 0.019001688 0.006927712 0.02376950 0.006841288
## 5 5 0.007035486 0.008418543 0.02497013 0.009194134
## 6 6 0.031704074 0.007440671 0.01638239 0.010026787
## 7 7 0.034649523 0.007606808 0.02289379 0.021474441
## 8 8 0.040120030 0.017361915 0.03912396 0.039786221
## 9 9 0.000000000 NaN 0.00000000 NaN</code></pre>
<div id="challenge-2" class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">
Challenge
</h3>
</div>
<div class="panel-body">
<p>Take a look at the <code>results</code> dataset. Is there something wrong? Why? What happened? Talk to your classmates and try to figure it out (5 min.).</p>
</div>
</div>
</div>
<div id="conditional-execution-if-and-else-statements" class="section level2">
<h2>Conditional Execution: if and else statements</h2>
<p>Sometimes we only want to execute certain code if the data fulfills some conditions. To do that we use <code>if</code> and <code>else</code> statements.</p>
<p>How <code>if</code> and <code>else</code> statements look like:</p>
<pre class="r"><code>if (this) {
# do that
} else if (that) {
# do something else
} else {
#
}</code></pre>
<p><strong>This</strong> and <strong>that</strong> in the previous chunk of code are boolean tests: code that returns TRUE/FALSE when the computer executes it. Some examples of boolean tests:</p>
<pre class="r"><code>10 == 2</code></pre>
<pre><code>## [1] FALSE</code></pre>
<pre class="r"><code>10 %in% c(2, 5, 13, 20, 10)</code></pre>
<pre><code>## [1] TRUE</code></pre>
<pre class="r"><code>10 == 2 & 10 %in% c(2, 5, 13, 20, 10)</code></pre>
<pre><code>## [1] FALSE</code></pre>
<pre class="r"><code>10 == 2 | 10 %in% c(2, 5, 13, 20, 10)</code></pre>
<pre><code>## [1] TRUE</code></pre>
<p>A short/silly example:</p>
<pre class="r"><code>some_numbers <- c(1, 4, 6, 10,12, 16, 45, 88, 102)
for (number in some_numbers) {
if (number < 10) {
print(paste0(number, " is smaller than 10"))
} else if (number < 50) {
print(paste0(number, " is smaller than 50 but greater or equal to 10"))
} else {
print(paste0(number, " is greater than 50"))
}
}</code></pre>
<pre><code>## [1] "1 is smaller than 10"
## [1] "4 is smaller than 10"
## [1] "6 is smaller than 10"
## [1] "10 is smaller than 50 but greater or equal to 10"
## [1] "12 is smaller than 50 but greater or equal to 10"
## [1] "16 is smaller than 50 but greater or equal to 10"
## [1] "45 is smaller than 50 but greater or equal to 10"
## [1] "88 is greater than 50"
## [1] "102 is greater than 50"</code></pre>
<p>Real example:</p>
<p>In the previous code where we estimated the same model for different groups of age we run into an issue with the last group: people in their 90s.</p>
<pre class="r"><code>table(turnout$age_new)</code></pre>
<pre><code>##
## 1 2 3 4 5 6 7 8 9
## 26 431 433 347 277 256 158 69 3</code></pre>
<p>Since there are only 3 people who are in their 90s we run out of degrees of freedom. Remember that df = #observations - 1 - #variables_in_the_model. Let’s adapt that code so that we only estimate the model in those cases we have enough degrees of freedom and prints a messages when that’s not the case.</p>
<pre class="r"><code>results2 <- data.frame(age_new = groups,
edu_coef = rep(NA, length(groups)),
edu_se = rep(NA, length(groups)),
inc_coef = rep(NA, length(groups)),
inc_se = rep(NA, length(groups)))
for (i in 1:length(groups)) {
gr <- groups[i]
sub_data <- filter(turnout, age_new == gr)
gr_model <- lm(model_formula, data = sub_data)
if (gr_model$df > 1) {
results2$edu_coef[i] <- coef(gr_model)[2]
results2$edu_se[i] <- sqrt(diag(vcov(gr_model)))[2]
results2$inc_coef[i] <- coef(gr_model)[3]
results2$inc_se[i] <- sqrt(diag(vcov(gr_model)))[3]
} else {
print(paste0("Not enough obs. to estimate the model for gr == ", gr))
}
}</code></pre>
<pre><code>## [1] "Not enough obs. to estimate the model for gr == 9"</code></pre>
<pre class="r"><code>results2</code></pre>
<pre><code>## age_new edu_coef edu_se inc_coef inc_se
## 1 1 0.140059313 0.082778700 0.01274892 0.039715750
## 2 2 0.063378607 0.009439463 0.02507891 0.010440232
## 3 3 0.021207718 0.007576099 0.02046039 0.008160295
## 4 4 0.019001688 0.006927712 0.02376950 0.006841288
## 5 5 0.007035486 0.008418543 0.02497013 0.009194134
## 6 6 0.031704074 0.007440671 0.01638239 0.010026787
## 7 7 0.034649523 0.007606808 0.02289379 0.021474441
## 8 8 0.040120030 0.017361915 0.03912396 0.039786221
## 9 9 NA NA NA NA</code></pre>
</div>
<!-- some extra javascript for older browsers -->
<script type="text/javascript" src="libs/polyfill.js"></script>
</div>
</div>
</div>
<script>
// add bootstrap table styles to pandoc tables
$(document).ready(function () {
$('tr.header').parent('thead').parent('table').addClass('table table-condensed');
});
</script>
<!-- dynamically load mathjax for compatibility with self-contained -->
<script>
(function () {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML";
document.getElementsByTagName("head")[0].appendChild(script);
})();
</script>
</body>
</html>