-
Notifications
You must be signed in to change notification settings - Fork 0
/
02-func-R.html
418 lines (414 loc) · 35.5 KB
/
02-func-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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="generator" content="pandoc">
<title>Software Carpentry: Programming with R</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-theme.css" />
<link rel="stylesheet" type="text/css" href="css/swc.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 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>
<article>
<div class="row">
<div class="col-md-10 col-md-offset-1">
<h1 class="title">Programming with R</h1>
<h2 class="subtitle">Creating functions</h2>
<div id="learning-objectives" class="objectives panel panel-warning">
<div class="panel-heading">
<h2><span class="glyphicon glyphicon-certificate"></span>Learning Objectives</h2>
</div>
<div class="panel-body">
<ul>
<li>Define a function that takes arguments.</li>
<li>Return a value from a function.</li>
<li>Test a function.</li>
<li>Explain what a call stack is, and trace changes to the call stack as functions are called.</li>
<li>Set default values for function arguments.</li>
<li>Explain why we should divide programs into small, single-purpose functions.</li>
</ul>
</div>
</div>
<p>If we only had one data set to analyze, it would probably be faster to load the file into a spreadsheet and use that to plot some simple statistics. But we have twelve files to check, and may have more in the future. In this lesson, we’ll learn how to write a function so that we can repeat several operations with a single command.</p>
<h3 id="defining-a-function">Defining a Function</h3>
<p>Let’s start by defining a function <code>fahr_to_kelvin</code> that converts temperatures from Fahrenheit to Kelvin:</p>
<pre class="sourceCode r"><code class="sourceCode r">fahr_to_kelvin <-<span class="st"> </span>function(temp) {
kelvin <-<span class="st"> </span>((temp -<span class="st"> </span><span class="dv">32</span>) *<span class="st"> </span>(<span class="dv">5</span> /<span class="st"> </span><span class="dv">9</span>)) +<span class="st"> </span><span class="fl">273.15</span>
<span class="kw">return</span>(kelvin)
}</code></pre>
<p>We define <code>fahr_to_kelvin</code> by assigning it to the output of <code>function</code>. The list of argument names are containted within parentheses. Next, the <a href="reference.html#function-body">body</a> of the function–the statements that are executed when it runs–is contained within curly braces (<code>{}</code>). The statements in the body are indented by two spaces. This makes the code easier to read but does not affect how the code operates.</p>
<p>When we call the function, the values we pass to it are assigned to those variables so that we can use them inside the function. Inside the function, we use a <a href="reference.html#return-statement">return statement</a> to send a result back to whoever asked for it.</p>
<div id="tip" class="callout panel panel-info">
<div class="panel-heading">
<h2><span class="glyphicon glyphicon-pushpin"></span>Tip</h2>
</div>
<div class="panel-body">
<p>One feature unique to R is that the return statement is not required. R automatically returns whichever variable is on the last line of the body of the function. Since we are just learning, we will explicitly define the return statement.</p>
</div>
</div>
<p>Let’s try running our function. Calling our own function is no different from calling any other function:</p>
<pre class="sourceCode r"><code class="sourceCode r"><span class="co"># freezing point of water</span>
<span class="kw">fahr_to_kelvin</span>(<span class="dv">32</span>)</code></pre>
<pre class="output"><code>[1] 273.15
</code></pre>
<pre class="sourceCode r"><code class="sourceCode r"><span class="co"># boiling point of water</span>
<span class="kw">fahr_to_kelvin</span>(<span class="dv">212</span>)</code></pre>
<pre class="output"><code>[1] 373.15
</code></pre>
<p>We’ve successfully called the function that we defined, and we have access to the value that we returned.</p>
<h3 id="composing-functions">Composing Functions</h3>
<p>Now that we’ve seen how to turn Fahrenheit into Kelvin, it’s easy to turn Kelvin into Celsius:</p>
<pre class="sourceCode r"><code class="sourceCode r">kelvin_to_celsius <-<span class="st"> </span>function(temp) {
celsius <-<span class="st"> </span>temp -<span class="st"> </span><span class="fl">273.15</span>
<span class="kw">return</span>(celsius)
}
<span class="co">#absolute zero in Celsius</span>
<span class="kw">kelvin_to_celsius</span>(<span class="dv">0</span>)</code></pre>
<pre class="output"><code>[1] -273.15
</code></pre>
<p>What about converting Fahrenheit to Celsius? We could write out the formula, but we don’t need to. Instead, we can <a href="reference.html#function-composition">compose</a> the two functions we have already created:</p>
<pre class="sourceCode r"><code class="sourceCode r">fahr_to_celsius <-<span class="st"> </span>function(temp) {
temp_k <-<span class="st"> </span><span class="kw">fahr_to_kelvin</span>(temp)
result <-<span class="st"> </span><span class="kw">kelvin_to_celsius</span>(temp_k)
<span class="kw">return</span>(result)
}
<span class="co"># freezing point of water in Celsius</span>
<span class="kw">fahr_to_celsius</span>(<span class="fl">32.0</span>)</code></pre>
<pre class="output"><code>[1] 0
</code></pre>
<p>This is our first taste of how larger programs are built: we define basic operations, then combine them in ever-large chunks to get the effect we want. Real-life functions will usually be larger than the ones shown here–typically half a dozen to a few dozen lines–but they shouldn’t ever be much longer than that, or the next person who reads it won’t be able to understand what’s going on.</p>
<div id="challenge---create-a-function" class="challenge panel panel-success">
<div class="panel-heading">
<h2><span class="glyphicon glyphicon-pencil"></span>Challenge - Create a function</h2>
</div>
<div class="panel-body">
<ul>
<li>In the last lesson, we learned to <strong>c</strong>oncatenate elements into a vector using the <code>c</code> function, e.g. <code>x <- c("A", "B", "C")</code> creates a vector <code>x</code> with three elements. Furthermore, we can extend that vector again using <code>c</code>, e.g. <code>y <- c(x, "D")</code> creates a vector <code>y</code> with four elements. Write a function called <code>fence</code> that takes two vectors as arguments, called <code>original</code> and <code>wrapper</code>, and returns a new vector that has the wrapper vector at the beginning and end of the original:</li>
</ul>
<pre class="sourceCode r"><code class="sourceCode r">best_practice <-<span class="st"> </span><span class="kw">c</span>(<span class="st">"Write"</span>, <span class="st">"programs"</span>, <span class="st">"for"</span>, <span class="st">"people"</span>, <span class="st">"not"</span>, <span class="st">"computers"</span>)
asterisk <-<span class="st"> "***"</span> <span class="co"># R interprets a variable with a single value as a vector</span>
<span class="co"># with one element.</span>
<span class="kw">fence</span>(best_practice, asterisk)</code></pre>
<pre class="output"><code>[1] "***" "Write" "programs" "for" "people" "not"
[7] "computers" "***"
</code></pre>
<ul>
<li>If the variable <code>v</code> refers to a vector, then <code>v[1]</code> is the vector’s first element and <code>v[length(v)]</code> is its last (the function <code>length</code> returns the number of elements in a vector). Write a function called <code>outside</code> that returns a vector made up of just the first and last elements of its input:</li>
</ul>
<pre class="sourceCode r"><code class="sourceCode r">dry_principle <-<span class="st"> </span><span class="kw">c</span>(<span class="st">"Don't"</span>, <span class="st">"repeat"</span>, <span class="st">"yourself"</span>, <span class="st">"or"</span>, <span class="st">"others"</span>)
<span class="kw">outside</span>(dry_principle)</code></pre>
<pre class="output"><code>[1] "Don't" "others"
</code></pre>
</div>
</div>
<h3 id="the-call-stack">The Call Stack</h3>
<p>Let’s take a closer look at what happens when we call <code>fahr_to_celsius(32)</code>. To make things clearer, we’ll start by putting the initial value 32 in a variable and store the final result in one as well:</p>
<pre class="sourceCode r"><code class="sourceCode r">original <-<span class="st"> </span><span class="dv">32</span>
final <-<span class="st"> </span><span class="kw">fahr_to_celsius</span>(original)</code></pre>
<p>The diagram below shows what memory looks like after the first line has been executed:</p>
<p><img src="fig/python-call-stack-01.svg" alt="Call Stack (Initial State)" /></p>
<p>When we call <code>fahr_to_celsius</code>, R <em>doesn’t</em> create the variable <code>temp</code> right away. Instead, it creates something called a <a href="reference.html#stack-frame">stack frame</a> to keep track of the variables defined by <code>fahr_to_kelvin</code>. Initially, this stack frame only holds the value of <code>temp</code>:</p>
<p><img src="fig/python-call-stack-02.svg" alt="Call Stack Immediately After First Function Call" /></p>
<p>When we call <code>fahr_to_kelvin</code> inside <code>fahr_to_celsius</code>, R creates another stack frame to hold <code>fahr_to_kelvin</code>’s variables:</p>
<p><img src="fig/python-call-stack-03.svg" alt="Call Stack During First Nested Function Call" /></p>
<p>It does this because there are now two variables in play called <code>temp</code>: the argument to <code>fahr_to_celsius</code>, and the argument to <code>fahr_to_kelvin</code>. Having two variables with the same name in the same part of the program would be ambiguous, so R (and every other modern programming language) creates a new stack frame for each function call to keep that function’s variables separate from those defined by other functions.</p>
<p>When the call to <code>fahr_to_kelvin</code> returns a value, R throws away <code>fahr_to_kelvin</code>’s stack frame and creates a new variable in the stack frame for <code>fahr_to_celsius</code> to hold the temperature in Kelvin:</p>
<p><img src="fig/python-call-stack-04.svg" alt="Call Stack After Return From First Nested Function Call" /></p>
<p>It then calls <code>kelvin_to_celsius</code>, which means it creates a stack frame to hold that function’s variables:</p>
<p><img src="fig/python-call-stack-05.svg" alt="Call Stack During Call to Second Nested Function" /></p>
<p>Once again, R throws away that stack frame when <code>kelvin_to_celsius</code> is done and creates the variable <code>result</code> in the stack frame for <code>fahr_to_celsius</code>:</p>
<p><img src="fig/python-call-stack-06.svg" alt="Call Stack After Second Nested Function Returns" /></p>
<p>Finally, when <code>fahr_to_celsius</code> is done, R throws away <em>its</em> stack frame and puts its result in a new variable called <code>final</code> that lives in the stack frame we started with:</p>
<p><img src="fig/python-call-stack-07.svg" alt="Call Stack After All Functions Have Finished" /></p>
<p>This final stack frame is always there; it holds the variables we defined outside the functions in our code. What it <em>doesn’t</em> hold is the variables that were in the various stack frames. If we try to get the value of <code>temp</code> after our functions have finished running, R tells us that there’s no such thing:</p>
<pre class="sourceCode r"><code class="sourceCode r">temp</code></pre>
<pre class="output"><code>Error in eval(expr, envir, enclos): object 'temp' not found
</code></pre>
<div id="tip-1" class="callout panel panel-info">
<div class="panel-heading">
<h2><span class="glyphicon glyphicon-pushpin"></span>Tip</h2>
</div>
<div class="panel-body">
<p>The explanation of the stack frame above was very general and the basic concept will help you understand most languages you try to program with. However, R has some unique aspects that can be exploited when performing more complicated operations. We will not be writing anything that requires knowledge of these more advanced concepts. In the future when you are comfortable writing functions in R, you can learn more by reading the <a href="http://cran.r-project.org/doc/manuals/r-release/R-lang.html#Environment-objects">R Language Manual</a> or this <a href="http://adv-r.had.co.nz/Environments.html">chapter</a> from <a href="http://adv-r.had.co.nz/">Advanced R Programming</a> by Hadley Wickham. For context, R uses the terminology “environments” instead of frames.</p>
</div>
</div>
<p>Why go to all this trouble? Well, here’s a function called <code>span</code> that calculates the difference between the mininum and maximum values in an array:</p>
<pre class="sourceCode r"><code class="sourceCode r">span <-<span class="st"> </span>function(a) {
diff <-<span class="st"> </span><span class="kw">max</span>(a) -<span class="st"> </span><span class="kw">min</span>(a)
<span class="kw">return</span>(diff)
}
dat <-<span class="st"> </span><span class="kw">read.csv</span>(<span class="dt">file =</span> <span class="st">"data/inflammation-01.csv"</span>, <span class="dt">header =</span> <span class="ot">FALSE</span>)
<span class="co"># span of inflammation data</span>
<span class="kw">span</span>(dat)</code></pre>
<pre class="output"><code>[1] 20
</code></pre>
<p>Notice <code>span</code> assigns a value to variable called <code>diff</code>. We might very well use a variable with the same name (<code>diff</code>) to hold the inflammation data:</p>
<pre class="sourceCode r"><code class="sourceCode r">diff <-<span class="st"> </span><span class="kw">read.csv</span>(<span class="dt">file =</span> <span class="st">"data/inflammation-01.csv"</span>, <span class="dt">header =</span> <span class="ot">FALSE</span>)
<span class="co"># span of inflammation data</span>
<span class="kw">span</span>(diff)</code></pre>
<pre class="output"><code>[1] 20
</code></pre>
<p>We don’t expect the variable <code>diff</code> to have the value 20 after this function call, so the name <code>diff</code> cannot refer to the same variable defined inside <code>span</code> as it does in as it does in the main body of our program (which R refers to as the global environment). And yes, we could probably choose a different name than <code>diff</code> for our variable in this case, but we don’t want to have to read every line of code of the R functions we call to see what variable names they use, just in case they change the values of our variables.</p>
<p>The big idea here is <a href="reference.html#encapsulation">encapsulation</a>, and it’s the key to writing correct, comprehensible programs. A function’s job is to turn several operations into one so that we can think about a single function call instead of a dozen or a hundred statements each time we want to do something. That only works if functions don’t interfere with each other; if they do, we have to pay attention to the details once again, which quickly overloads our short-term memory.</p>
<div id="challenge---following-the-call-stack" class="challenge panel panel-success">
<div class="panel-heading">
<h2><span class="glyphicon glyphicon-pencil"></span>Challenge - Following the call stack</h2>
</div>
<div class="panel-body">
<ul>
<li>We previously wrote functions called <code>fence</code> and <code>outside</code>. Draw a diagram showing how the call stack changes when we run the following:</li>
</ul>
<pre class="sourceCode r"><code class="sourceCode r">inner_vec <-<span class="st"> "carbon"</span>
outer_vec <-<span class="st"> "+"</span>
result <-<span class="st"> </span><span class="kw">outside</span>(<span class="kw">fence</span>(inner_vec, outer_vec))</code></pre>
</div>
</div>
<h3 id="testing-and-documenting">Testing and Documenting</h3>
<p>Once we start putting things in functions so that we can re-use them, we need to start testing that those functions are working correctly. To see how to do this, let’s write a function to center a dataset around a particular value:</p>
<pre class="sourceCode r"><code class="sourceCode r">center <-<span class="st"> </span>function(data, desired) {
new_data <-<span class="st"> </span>(data -<span class="st"> </span><span class="kw">mean</span>(data)) +<span class="st"> </span>desired
<span class="kw">return</span>(new_data)
}</code></pre>
<p>We could test this on our actual data, but since we don’t know what the values ought to be, it will be hard to tell if the result was correct. Instead, let’s create a vector of 0s and then center that around 3. This will make it simple to see if our function is working as expected:</p>
<pre class="sourceCode r"><code class="sourceCode r">z <-<span class="st"> </span><span class="kw">c</span>(<span class="dv">0</span>, <span class="dv">0</span>, <span class="dv">0</span>, <span class="dv">0</span>)
z</code></pre>
<pre class="output"><code>[1] 0 0 0 0
</code></pre>
<pre class="sourceCode r"><code class="sourceCode r"><span class="kw">center</span>(z, <span class="dv">3</span>)</code></pre>
<pre class="output"><code>[1] 3 3 3 3
</code></pre>
<p>That looks right, so let’s try center on our real data. We’ll center the inflammation data from day 4 around 0:</p>
<pre class="sourceCode r"><code class="sourceCode r">dat <-<span class="st"> </span><span class="kw">read.csv</span>(<span class="dt">file =</span> <span class="st">"data/inflammation-01.csv"</span>, <span class="dt">header =</span> <span class="ot">FALSE</span>)
centered <-<span class="st"> </span><span class="kw">center</span>(dat[, <span class="dv">4</span>], <span class="dv">0</span>)
<span class="kw">head</span>(centered)</code></pre>
<pre class="output"><code>[1] 1.25 -0.75 1.25 -1.75 1.25 0.25
</code></pre>
<p>It’s hard to tell from the default output whether the result is correct, but there are a few simple tests that will reassure us:</p>
<pre class="sourceCode r"><code class="sourceCode r"><span class="co"># original min</span>
<span class="kw">min</span>(dat[, <span class="dv">4</span>])</code></pre>
<pre class="output"><code>[1] 0
</code></pre>
<pre class="sourceCode r"><code class="sourceCode r"><span class="co"># original mean</span>
<span class="kw">mean</span>(dat[, <span class="dv">4</span>])</code></pre>
<pre class="output"><code>[1] 1.75
</code></pre>
<pre class="sourceCode r"><code class="sourceCode r"><span class="co"># original max</span>
<span class="kw">max</span>(dat[, <span class="dv">4</span>])</code></pre>
<pre class="output"><code>[1] 3
</code></pre>
<pre class="sourceCode r"><code class="sourceCode r"><span class="co"># centered min</span>
<span class="kw">min</span>(centered)</code></pre>
<pre class="output"><code>[1] -1.75
</code></pre>
<pre class="sourceCode r"><code class="sourceCode r"><span class="co"># centered mean</span>
<span class="kw">mean</span>(centered)</code></pre>
<pre class="output"><code>[1] 0
</code></pre>
<pre class="sourceCode r"><code class="sourceCode r"><span class="co"># centered max</span>
<span class="kw">max</span>(centered)</code></pre>
<pre class="output"><code>[1] 1.25
</code></pre>
<p>That seems almost right: the original mean was about 1.75, so the lower bound from zero is now about -1.75. The mean of the centered data is 0. We can even go further and check that the standard deviation hasn’t changed:</p>
<pre class="sourceCode r"><code class="sourceCode r"><span class="co"># original standard deviation</span>
<span class="kw">sd</span>(dat[, <span class="dv">4</span>])</code></pre>
<pre class="output"><code>[1] 1.067628
</code></pre>
<pre class="sourceCode r"><code class="sourceCode r"><span class="co"># centerted standard deviation</span>
<span class="kw">sd</span>(centered)</code></pre>
<pre class="output"><code>[1] 1.067628
</code></pre>
<p>Those values look the same, but we probably wouldn’t notice if they were different in the sixth decimal place. Let’s do this instead:</p>
<pre class="sourceCode r"><code class="sourceCode r"><span class="co"># difference in standard deviations before and after</span>
<span class="kw">sd</span>(dat[, <span class="dv">4</span>]) -<span class="st"> </span><span class="kw">sd</span>(centered)</code></pre>
<pre class="output"><code>[1] 0
</code></pre>
<p>Sometimes, a very small difference can be detected due to rounding at very low decimal places. R has a useful function for comparing two objects allowing for rounding errors, <code>all.equal</code>:</p>
<pre class="sourceCode r"><code class="sourceCode r"><span class="kw">all.equal</span>(<span class="kw">sd</span>(dat[, <span class="dv">4</span>]), <span class="kw">sd</span>(centered))</code></pre>
<pre class="output"><code>[1] TRUE
</code></pre>
<p>It’s still possible that our function is wrong, but it seems unlikely enough that we should probably get back to doing our analysis. We have one more task first, though: we should write some <a href="reference.html#documentation">documentation</a> for our function to remind ourselves later what it’s for and how to use it.</p>
<p>A common way to put documentation in software is to add <a href="reference.html#comment">comments</a> like this:</p>
<pre class="sourceCode r"><code class="sourceCode r">center <-<span class="st"> </span>function(data, desired) {
<span class="co"># return a new vector containing the original data centered around the</span>
<span class="co"># desired value.</span>
<span class="co"># Example: center(c(1, 2, 3), 0) => c(-1, 0, 1)</span>
new_data <-<span class="st"> </span>(data -<span class="st"> </span><span class="kw">mean</span>(data)) +<span class="st"> </span>desired
<span class="kw">return</span>(new_data)
}</code></pre>
<div id="tip-2" class="callout panel panel-info">
<div class="panel-heading">
<h2><span class="glyphicon glyphicon-pushpin"></span>Tip</h2>
</div>
<div class="panel-body">
<p>Formal documentation for R functions is written in separate <code>.Rd</code> using a markup language similar to <a href="http://www.latex-project.org/">LaTeX</a>. You see the result of this documentation when you look at the help file for a given function, e.g. <code>?read.csv</code>. The <a href="http://cran.r-project.org/web/packages/roxygen2/vignettes/rd.html">roxygen2</a> package allows R coders to write documentation alongside the function code and then process it into the appropriate <code>.Rd</code> files. You will want to switch to this more formal method of writing documentation when you start writing more complicated R projects.</p>
</div>
</div>
<div id="challenge---a-more-advanced-function" class="challenge panel panel-success">
<div class="panel-heading">
<h2><span class="glyphicon glyphicon-pencil"></span>Challenge - A more advanced function</h2>
</div>
<div class="panel-body">
<ul>
<li>Write a function called <code>analyze</code> that takes a filename as a argument and displays the three graphs produced in the <a href="01-starting-with-data.html">previous lesson</a> (average, min and max inflammation over time). <code>analyze("data/inflammation-01.csv")</code> should produce the graphs already shown, while <code>analyze("data/inflammation-02.csv")</code> should produce corresponding graphs for the second data set. Be sure to document your function with comments.</li>
<li>Write a function <code>rescale</code> that takes a vector as input and returns a corresponding vector of values scaled to lie in the range 0 to 1. (If <span class="math"><em>L</em></span> and <span class="math"><em>H</em></span> are the lowest and highest values in the original vector, then the replacement for a value <span class="math"><em>v</em></span> should be <span class="math">(<em>v</em> − <em>L</em>) / (<em>H</em> − <em>L</em>)</span>.) Be sure to document your function with comments.</li>
<li>Test that your <code>rescale</code> function is working properly using <code>min</code>, <code>max</code>, and <code>plot</code>.</li>
</ul>
</div>
</div>
<h3 id="defining-defaults">Defining Defaults</h3>
<p>We have passed arguments to functions in two ways: directly, as in <code>dim(dat)</code>, and by name, as in <code>read.csv(file = "data/inflammation-01.csv", header = FALSE)</code>. In fact, we can pass the arguments to <code>read.csv</code> without naming them:</p>
<pre class="sourceCode r"><code class="sourceCode r">dat <-<span class="st"> </span><span class="kw">read.csv</span>(<span class="st">"data/inflammation-01.csv"</span>, <span class="ot">FALSE</span>)</code></pre>
<p>However, the position of the arguments matters if they are not named.</p>
<pre class="sourceCode r"><code class="sourceCode r">dat <-<span class="st"> </span><span class="kw">read.csv</span>(<span class="dt">header =</span> <span class="ot">FALSE</span>, <span class="dt">file =</span> <span class="st">"data/inflammation-01.csv"</span>)
dat <-<span class="st"> </span><span class="kw">read.csv</span>(<span class="ot">FALSE</span>, <span class="st">"data/inflammation-01.csv"</span>)</code></pre>
<pre class="output"><code>Error in read.table(file = file, header = header, sep = sep, quote = quote, : 'file' must be a character string or connection
</code></pre>
<p>To understand what’s going on, and make our own functions easier to use, let’s re-define our <code>center</code> function like this:</p>
<pre class="sourceCode r"><code class="sourceCode r">center <-<span class="st"> </span>function(data, <span class="dt">desired =</span> <span class="dv">0</span>) {
<span class="co"># return a new vector containing the original data centered around the</span>
<span class="co"># desired value (0 by default).</span>
<span class="co"># Example: center(c(1, 2, 3), 0) => c(-1, 0, 1)</span>
new_data <-<span class="st"> </span>(data -<span class="st"> </span><span class="kw">mean</span>(data)) +<span class="st"> </span>desired
<span class="kw">return</span>(new_data)
}</code></pre>
<p>The key change is that the second argument is now written <code>desired = 0</code> instead of just <code>desired</code>. If we call the function with two arguments, it works as it did before:</p>
<pre class="sourceCode r"><code class="sourceCode r">test_data <-<span class="st"> </span><span class="kw">c</span>(<span class="dv">0</span>, <span class="dv">0</span>, <span class="dv">0</span>, <span class="dv">0</span>)
<span class="kw">center</span>(test_data, <span class="dv">3</span>)</code></pre>
<pre class="output"><code>[1] 3 3 3 3
</code></pre>
<p>But we can also now call <code>center()</code> with just one argument, in which case <code>desired</code> is automatically assigned the default value of <code>0</code>:</p>
<pre class="sourceCode r"><code class="sourceCode r">more_data <-<span class="st"> </span><span class="dv">5</span> +<span class="st"> </span>test_data
more_data</code></pre>
<pre class="output"><code>[1] 5 5 5 5
</code></pre>
<pre class="sourceCode r"><code class="sourceCode r"><span class="kw">center</span>(more_data)</code></pre>
<pre class="output"><code>[1] 0 0 0 0
</code></pre>
<p>This is handy: if we usually want a function to work one way, but occasionally need it to do something else, we can allow people to pass an argument when they need to but provide a default to make the normal case easier.</p>
<p>The example below shows how R matches values to arguments</p>
<pre class="sourceCode r"><code class="sourceCode r">display <-<span class="st"> </span>function(<span class="dt">a =</span> <span class="dv">1</span>, <span class="dt">b =</span> <span class="dv">2</span>, <span class="dt">c =</span> <span class="dv">3</span>) {
result <-<span class="st"> </span><span class="kw">c</span>(a, b, c)
<span class="kw">names</span>(result) <-<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="co"># This names each element of the vector</span>
<span class="kw">return</span>(result)
}
<span class="co"># no arguments</span>
<span class="kw">display</span>()</code></pre>
<pre class="output"><code>a b c
1 2 3
</code></pre>
<pre class="sourceCode r"><code class="sourceCode r"><span class="co"># one argument</span>
<span class="kw">display</span>(<span class="dv">55</span>)</code></pre>
<pre class="output"><code> a b c
55 2 3
</code></pre>
<pre class="sourceCode r"><code class="sourceCode r"><span class="co"># two arguments</span>
<span class="kw">display</span>(<span class="dv">55</span>, <span class="dv">66</span>)</code></pre>
<pre class="output"><code> a b c
55 66 3
</code></pre>
<pre class="sourceCode r"><code class="sourceCode r"><span class="co"># three arguments</span>
<span class="kw">display</span> (<span class="dv">55</span>, <span class="dv">66</span>, <span class="dv">77</span>)</code></pre>
<pre class="output"><code> a b c
55 66 77
</code></pre>
<p>As this example shows, arguments are matched from left to right, and any that haven’t been given a value explicitly get their default value. We can override this behavior by naming the value as we pass it in:</p>
<pre class="sourceCode r"><code class="sourceCode r"><span class="co"># only setting the value of c</span>
<span class="kw">display</span>(<span class="dt">c =</span> <span class="dv">77</span>)</code></pre>
<pre class="output"><code> a b c
1 2 77
</code></pre>
<div id="tip-3" class="callout panel panel-info">
<div class="panel-heading">
<h2><span class="glyphicon glyphicon-pushpin"></span>Tip</h2>
</div>
<div class="panel-body">
<p>To be precise, R has three ways that arguments supplied</p>
<p>by you are matched to the <em>formal arguments</em> of the function definition</p>
<ol style="list-style-type: decimal">
<li>by complete name,</li>
<li>by partial name (matching on initial <em>n</em> characters of the argument name), and</li>
<li>by position.</li>
</ol>
<p>Arguments are matched in the manner outlined above in <em>that order</em>: by complete name, then by partial matching of names, and finally by position.</p>
</div>
</div>
<p>With that in hand, let’s look at the help for <code>read.csv()</code>:</p>
<pre class="sourceCode r"><code class="sourceCode r">?read.csv</code></pre>
<p>There’s a lot of information there, but the most important part is the first couple of lines:</p>
<pre class="sourceCode r"><code class="sourceCode r"><span class="kw">read.csv</span>(file, <span class="dt">header =</span> <span class="ot">TRUE</span>, <span class="dt">sep =</span> <span class="st">","</span>, <span class="dt">quote =</span> <span class="st">"</span><span class="ch">\"</span><span class="st">"</span>,
<span class="dt">dec =</span> <span class="st">"."</span>, <span class="dt">fill =</span> <span class="ot">TRUE</span>, <span class="dt">comment.char =</span> <span class="st">""</span>, ...)</code></pre>
<p>This tells us that <code>read.csv()</code> has one argument, <code>file</code>, that doesn’t have a default value, and six others that do. Now we understand why the following gives an error:</p>
<pre class="sourceCode r"><code class="sourceCode r">dat <-<span class="st"> </span><span class="kw">read.csv</span>(<span class="ot">FALSE</span>, <span class="st">"data/inflammation-01.csv"</span>)</code></pre>
<pre class="output"><code>Error in read.table(file = file, header = header, sep = sep, quote = quote, : 'file' must be a character string or connection
</code></pre>
<p>It fails because <code>FALSE</code> is assigned to <code>file</code> and the filename is assigned to the argument <code>header</code>.</p>
<div id="challenge---a-function-with-default-argument-values" class="challenge panel panel-success">
<div class="panel-heading">
<h2><span class="glyphicon glyphicon-pencil"></span>Challenge - A function with default argument values</h2>
</div>
<div class="panel-body">
<ul>
<li>Rewrite the <code>rescale</code> function so that it scales a vector to lie between 0 and 1 by default, but will allow the caller to specify lower and upper bounds if they want. Compare your implementation to your neighbor’s: do the two functions always behave the same way?</li>
</ul>
</div>
</div>
<div id="key-points" class="callout panel panel-info">
<div class="panel-heading">
<h2><span class="glyphicon glyphicon-pushpin"></span>Key Points</h2>
</div>
<div class="panel-body">
<ul>
<li>Define a function using <code>name <- function(...args...) {...body...}</code>.</li>
<li>Call a function using <code>name(...values...)</code>.</li>
<li>Each time a function is called, a new stack frame is created on the <a href="reference.html#call-stack">call stack</a> to hold its arguments and local variables.</li>
<li>R looks for variables in the current stack frame before looking for them at the top level.</li>
<li>Use <code>help(thing)</code> to view help for something.</li>
<li>Put comments at the beginning of functions to provide help for that function.</li>
<li>Annotate your code!</li>
<li>Specify default values for arguments when defining a function using <code>name = value</code> in the argument list.</li>
<li>Arguments can be passed by matching based on name, by position, or by omitting them (in which case the default value is used).</li>
</ul>
</div>
</div>
<div id="next-steps" class="callout panel panel-info">
<div class="panel-heading">
<h2><span class="glyphicon glyphicon-pushpin"></span>Next Steps</h2>
</div>
<div class="panel-body">
<p>We now have a function called analyze to visualize a single data set. We could use it to explore all 12 of our current data sets like this:</p>
<pre class="sourceCode r"><code class="sourceCode r"><span class="kw">analyze</span>(<span class="st">"data/inflammation-01.csv"</span>)
<span class="kw">analyze</span>(<span class="st">"data/inflammation-02.csv"</span>)
<span class="co">#...</span>
<span class="kw">analyze</span>(<span class="st">"data/inflammation-12.csv"</span>)</code></pre>
<p>but the chances of us typing all 12 filenames correctly aren’t great, and we’ll be even worse off if we get another hundred files. What we need is a way to tell R to do something once for each file, and that will be the subject of the next lesson.</p>
</div>
</div>
</div>
</div>
</article>
<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/r-novice-inflammation">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="css/bootstrap/bootstrap-js/bootstrap.js"></script>
</body>
</html>