forked from griffinp/r-novice-owls
-
Notifications
You must be signed in to change notification settings - Fork 1
/
10-control-flow.html
202 lines (196 loc) · 14.9 KB
/
10-control-flow.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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="generator" content="pandoc">
<title>Software Carpentry: R for reproducible scientific analysis</title>
<link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" type="text/css" href="css/bootstrap/bootstrap.css" />
<link rel="stylesheet" type="text/css" href="css/bootstrap/bootstrap-responsive.css" />
<link rel="stylesheet" type="text/css" href="css/swc.css" />
<link rel="stylesheet" type="text/css" href="css/swc-workshop-and-lesson.css" />
<link rel="stylesheet" type="text/css" href="css/lesson.css" />
<link rel="alternate" type="application/rss+xml" title="Software Carpentry Blog" href="http://software-carpentry.org/feed.xml"/>
<meta charset="UTF-8" />
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body class="lesson">
<div class="container container-full-width card">
<div class="banner">
<a href="http://software-carpentry.org" title="Software Carpentry">
<img alt="Software Carpentry banner" src="img/software-carpentry-banner.png" />
</a>
</div>
<div class="row-fluid">
<div class="span10 offset1">
<h1 class="title">R for reproducible scientific analysis</h1>
<h2 class="subtitle">Control flow</h2>
<div id="learning-objectives" class="objectives">
<h2>Learning Objectives</h2>
<ul>
<li>Write conditional statements with <code>if</code> and <code>else</code>.</li>
<li>Write and understand <code>while</code> and <code>for</code> loops.</li>
</ul>
</div>
<p>Often when we're coding we want to control the flow of our actions. This can be done by setting actions to occur only if a condition or a set of conditions are met. Alternatively, we can also set an action to occur a particular number of times.</p>
<p>There are several ways you can control flow in R. For conditional statements, the most commonly used approaches are the constructs:</p>
<pre class="sourceCode r"><code class="sourceCode r"><span class="co"># if</span>
if (condition is true) {
perform action
}
<span class="co"># if ... else</span>
if (condition is true) {
perform action
}
else { <span class="co"># that is, if the condition is false,</span>
perform alternative action
}
</code></pre>
<p>Say, for example, that we want R to print a message if a variable <code>x</code> has a particular value:</p>
<pre class="sourceCode r"><code class="sourceCode r"><span class="co"># sample a random number from a Poisson distribution</span>
<span class="co"># with a mean (lambda) of 8</span>
x <-<span class="st"> </span><span class="kw">rpois</span>(<span class="dv">1</span>, <span class="dt">lambda=</span><span class="dv">8</span>)
if (x >=<span class="st"> </span><span class="dv">10</span>) {
<span class="kw">print</span>(<span class="st">"x is greater than or equal to 10"</span>)
}
x</code></pre>
<p>Note you may not get the same output as your neighbour because you may be sampling different random numbers from the same distribution.</p>
<p>Let's set a seed so that we all generate the same 'pseudo-random' number, and then print more information:</p>
<pre class="sourceCode r"><code class="sourceCode r"><span class="kw">set.seed</span>(<span class="dv">10</span>)
x <-<span class="st"> </span><span class="kw">rpois</span>(<span class="dv">1</span>, <span class="dt">lambda=</span><span class="dv">8</span>)
if (x >=<span class="st"> </span><span class="dv">10</span>) {
<span class="kw">print</span>(<span class="st">"x is greater than or equal to 10"</span>)
} else if (x ><span class="st"> </span><span class="dv">5</span>) {
<span class="kw">print</span>(<span class="st">"x is greater than 5"</span>)
} else {
<span class="kw">print</span>(<span class="st">"x is less than 5"</span>)
}</code></pre>
<pre class="output"><code>[1] "x is greater than 5"</code></pre>
<div id="tip-pseudo-random-numbers" class="callout">
<h4>Tip: pseudo-random numbers</h4>
<p>In the above case, the function <code>rpois</code> generates a random number following a Poisson distribution with a mean (i.e. lambda) of 8. The function <code>set.seed</code> guarantees that all machines that use the seed 10 as an input, will generate the exact same 'pseudo-random' number (<a href="http://en.wikibooks.org/wiki/R_Programming/Random_Number_Generation">more about pseudo-random numbers</a>). Now, looking at x we see that it takes the value 8 (you should get the exact same number).</p>
</div>
<p><strong>Important:</strong> when R evaluates the condition inside <code>if</code> statements, it is looking for a logical element, i.e., <code>TRUE</code> or <code>FALSE</code>. This can cause some headaches for beginners. For example:</p>
<pre class="sourceCode r"><code class="sourceCode r">x <-<span class="st"> </span><span class="dv">4</span> ==<span class="st"> </span><span class="dv">3</span>
if (x) {
<span class="st">"4 equals 3"</span>
}</code></pre>
<p>As we can see, the message was not printed because the vector x is <code>FALSE</code></p>
<pre class="sourceCode r"><code class="sourceCode r">x <-<span class="st"> </span><span class="dv">4</span> ==<span class="st"> </span><span class="dv">3</span>
x</code></pre>
<pre class="output"><code>[1] FALSE</code></pre>
<div id="challenge-1" class="challenge">
<h4>Challenge 1</h4>
<p>Use an <code>if</code> statement to print a suitable message reporting whether there are any records from 2002 in the <code>gapminder</code> dataset. Now do the same for 2012.</p>
</div>
<p>Did anyone get a warning message like this?</p>
<pre class="output"><code>Warning message:
In if (gapminder$year == 2012) { :
the condition has length > 1 and only the first element will be used</code></pre>
<p>If your condition evaluates to a vector with more than one logical element, the function <code>if</code> will still run, but will only evaluate the condition in the first element. Here you need to make sure your condition is of length 1.</p>
<blockquote>
<h4 id="tip-any-and-all">Tip: <code>any</code> and <code class="callout">all</code></h4>
<p>The <code>any</code> function will return TRUE if at least one TRUE value is found within a vector, otherwise it will return <code>FALSE</code>. This can be used in a similar way to the <code>%in%</code> operator. The function <code>all</code>, as the name suggests, will only return <code>TRUE</code> if all values in the vector are <code>TRUE</code>.</p>
</blockquote>
<h3 id="repeating-operations">Repeating operations</h3>
<p>Sometimes you will find yourself needing to repeat an operation until a certain condition is met. You can do this with a <code>while</code> loop.</p>
<pre class="sourceCode r"><code class="sourceCode r">while(this condition is true){
do a thing
} </code></pre>
<p>Let's try an example, shall we? We'll try to come up with some simple code that generates random numbers from a uniform distribution (the <code>runif</code> function) between 0 and 1 until it gets one that's less than 0.1.</p>
<pre class="sourceCode r"><code class="sourceCode r">while(z ><span class="st"> </span><span class="fl">0.1</span>){
z <-<span class="st"> </span><span class="kw">runif</span>(<span class="dv">1</span>)
<span class="kw">print</span>(z)
}</code></pre>
<pre class="output"><code>Error: object 'z' not found</code></pre>
<p>But wait, that doesn't work! What's the problem?</p>
<p>The problem is that we haven't defined <code>z</code>, and so the very first time the while loop's condition is checked (<code>z > 0.1</code>), <code>while</code> just says "Okay, that's not true so I'm not going to execute this block of code". The same thing would have happened if we defined <code>z</code> to be anything less than 0.1. Let's fix it.</p>
<pre class="sourceCode r"><code class="sourceCode r">z <-<span class="st"> </span><span class="dv">1</span>
while(z ><span class="st"> </span><span class="fl">0.1</span>){
z <-<span class="st"> </span><span class="kw">runif</span>(<span class="dv">1</span>)
<span class="kw">print</span>(z)
}</code></pre>
<div id="challenge-2" class="challenge">
<h4>Challenge 2</h4>
<p>Use a <code>while</code> loop to construct a vector called 'pet_list' with the value: 'cat', 'dog', 'dog', 'dog', 'dog' (N.B. using a loop may not be the most efficient way to do this, but it illustrates the principle!)</p>
</div>
<p><code>while</code> loops will not always be appropriate. If you want to iterate over a set of values, when the order of iteration is important, and perform the same operation on each, a <code>for</code> loop will do the job. We saw <code>for</code> loops in the shell lessons earlier. This is the most flexible of looping operations, but therefore also the hardest to use correctly. Avoid using <code>for</code> loops unless the order of iteration is important: i.e. the calculation at each iteration depends on the results of previous iterations.</p>
<p>The basic structure of a <code>for</code> loop is:</p>
<pre class="sourceCode r"><code class="sourceCode r">for(iterator in set of values){
do a thing
}</code></pre>
<p>For example:</p>
<pre class="sourceCode r"><code class="sourceCode r">for(i in <span class="dv">1</span>:<span class="dv">10</span>){
<span class="kw">print</span>(i)
}</code></pre>
<p>The <code>1:10</code> bit creates a vector on the fly; you can iterate over any other vector as well.</p>
<p>We can use a <code>for</code> loop nested within another <code>for</code> loop to iterate over two things at once.</p>
<pre class="sourceCode r"><code class="sourceCode r">for (i in <span class="dv">1</span>:<span class="dv">5</span>){
for(j in <span class="kw">c</span>(<span class="st">'a'</span>, <span class="st">'b'</span>, <span class="st">'c'</span>, <span class="st">'d'</span>, <span class="st">'e'</span>)){
<span class="kw">print</span>(<span class="kw">paste</span>(i,j))
}
}</code></pre>
<p>Rather than printing the results, we could write the loop output to a new object.</p>
<pre class="sourceCode r"><code class="sourceCode r">output_vector <-<span class="st"> </span><span class="kw">c</span>()
for (i in <span class="dv">1</span>:<span class="dv">5</span>){
for(j in <span class="kw">c</span>(<span class="st">'a'</span>, <span class="st">'b'</span>, <span class="st">'c'</span>, <span class="st">'d'</span>, <span class="st">'e'</span>)){
temp_output <-<span class="st"> </span><span class="kw">paste</span>(i, j)
output_vector <-<span class="st"> </span><span class="kw">c</span>(output_vector, temp_output)
}
}
output_vector</code></pre>
<pre class="output"><code> [1] "1 a" "1 b" "1 c" "1 d" "1 e" "2 a" "2 b" "2 c"
[9] "2 d" "2 e" "3 a" "3 b" "3 c" "3 d" "3 e" "4 a"
[17] "4 b" "4 c" "4 d" "4 e" "5 a" "5 b" "5 c" "5 d"
[25] "5 e"</code></pre>
<p>This approach can be useful, but 'growing your results' (building the result object incrementally) is computationally inefficient, so avoid it when you are iterating through a lot of values.</p>
<div id="tip-dont-grow-your-results" class="callout">
<h4>Tip: don't grow your results</h4>
<p>One of the biggest things that trips up novices and experienced R users alike, is building a results object (vector, list, matrix, data frame) as your for loop progresses. Computers are very bad at handling this, so your calculations can very quickly slow to a crawl. It's much better to define an empty results object before hand of the appropriate dimensions. So if you know the end result will be stored in a matrix like above, create an empty matrix with 5 row and 5 columns, then at each iteration store the results in the appropriate location.</p>
</div>
<p>A better way is to define your (empty) output object before filling in the values. For this example, it looks more involved, but is still more efficient.</p>
<pre class="sourceCode r"><code class="sourceCode r">output_matrix <-<span class="st"> </span><span class="kw">matrix</span>(<span class="dt">nrow=</span><span class="dv">5</span>, <span class="dt">ncol=</span><span class="dv">5</span>)
j_vector <-<span class="st"> </span><span class="kw">c</span>(<span class="st">'a'</span>, <span class="st">'b'</span>, <span class="st">'c'</span>, <span class="st">'d'</span>, <span class="st">'e'</span>)
for (i in <span class="dv">1</span>:<span class="dv">5</span>){
for(j in <span class="dv">1</span>:<span class="dv">5</span>){
temp_j_value <-<span class="st"> </span>j_vector[j]
temp_output <-<span class="st"> </span><span class="kw">paste</span>(i, temp_j_value)
output_matrix[i, j] <-<span class="st"> </span>temp_output
}
}
output_vector2 <-<span class="st"> </span><span class="kw">as.vector</span>(output_matrix)
output_vector2</code></pre>
<div id="challenge-3" class="challenge">
<h4>Challenge 3</h4>
<p>Compare the objects output_vector and output_vector2. Are they the same? If not, why not? How would you change the last block of code to make output_vector2 the same as output_vector?</p>
</div>
<div id="challenge-4" class="challenge">
<h4>Challenge 4</h4>
<p>Write a script that loops through the <code>gapminder</code> data by continent and prints out whether the mean life expectancy is smaller or larger than 50 years.</p>
</div>
<div id="challenge-5" class="challenge">
<h4>Challenge 5</h4>
<p>Modify the script from Challenge 4 to also loop over each country. This time print out whether the life expectancy is smaller than 50, between 50 and 70, or greater than 70.</p>
</div>
<div id="challenge-6---advanced" class="challenge">
<h4>Challenge 6 - Advanced</h4>
<p>Write a script that loops over each country in the <code>gapminder</code> dataset, tests whether the country starts with a 'B', and graphs life expectancy against time as a line graph if the mean life expectancy is under 50 years.</p>
</div>
</div>
</div>
<div class="footer">
<a class="label swc-blue-bg" href="http://software-carpentry.org">Software Carpentry</a>
<a class="label swc-blue-bg" href="https://github.com/swcarpentry/lesson-template">Source</a>
<a class="label swc-blue-bg" href="mailto:[email protected]">Contact</a>
<a class="label swc-blue-bg" href="LICENSE.html">License</a>
</div>
</div>
<!-- Javascript placed at the end of the document so the pages load faster -->
<script src="http://software-carpentry.org/v5/js/jquery-1.9.1.min.js"></script>
<script src="http://software-carpentry.org/v5/js/bootstrap/bootstrap.min.js"></script>
</body>
</html>