forked from datacarpentry/R-ecology-lesson
-
Notifications
You must be signed in to change notification settings - Fork 0
/
01-intro-to-R.html
616 lines (542 loc) · 36.3 KB
/
01-intro-to-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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
<!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="author" content="Data Carpentry contributors" />
<title>Introduction to R</title>
<script src="site_libs/jquery-1.11.3/jquery.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="site_libs/bootstrap-3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<script src="site_libs/bootstrap-3.3.5/js/bootstrap.min.js"></script>
<script src="site_libs/bootstrap-3.3.5/shim/html5shiv.min.js"></script>
<script src="site_libs/bootstrap-3.3.5/shim/respond.min.js"></script>
<script src="site_libs/jqueryui-1.11.4/jquery-ui.min.js"></script>
<link href="site_libs/tocify-1.9.1/jquery.tocify.css" rel="stylesheet" />
<script src="site_libs/tocify-1.9.1/jquery.tocify.js"></script>
<script src="site_libs/navigation-1.1/tabsets.js"></script>
<link href="site_libs/font-awesome-4.5.0/css/font-awesome.min.css" rel="stylesheet" />
<style type="text/css">code{white-space: pre;}</style>
<style type="text/css">
div.sourceCode { overflow-x: auto; }
table.sourceCode, tr.sourceCode, td.lineNumbers, td.sourceCode {
margin: 0; padding: 0; vertical-align: baseline; border: none; }
table.sourceCode { width: 100%; line-height: 100%; background-color: #f8f8f8; }
td.lineNumbers { text-align: right; padding-right: 4px; padding-left: 4px; color: #aaaaaa; border-right: 1px solid #aaaaaa; }
td.sourceCode { padding-left: 5px; }
pre, code { background-color: #f8f8f8; }
code > span.kw { color: #204a87; font-weight: bold; } /* Keyword */
code > span.dt { color: #204a87; } /* DataType */
code > span.dv { color: #0000cf; } /* DecVal */
code > span.bn { color: #0000cf; } /* BaseN */
code > span.fl { color: #0000cf; } /* Float */
code > span.ch { color: #4e9a06; } /* Char */
code > span.st { color: #4e9a06; } /* String */
code > span.co { color: #8f5902; font-style: italic; } /* Comment */
code > span.ot { color: #8f5902; } /* Other */
code > span.al { color: #ef2929; } /* Alert */
code > span.fu { color: #000000; } /* Function */
code > span.er { color: #a40000; font-weight: bold; } /* Error */
code > span.wa { color: #8f5902; font-weight: bold; font-style: italic; } /* Warning */
code > span.cn { color: #000000; } /* Constant */
code > span.sc { color: #000000; } /* SpecialChar */
code > span.vs { color: #4e9a06; } /* VerbatimString */
code > span.ss { color: #4e9a06; } /* SpecialString */
code > span.im { } /* Import */
code > span.va { color: #000000; } /* Variable */
code > span.cf { color: #204a87; font-weight: bold; } /* ControlFlow */
code > span.op { color: #ce5c00; font-weight: bold; } /* Operator */
code > span.pp { color: #8f5902; font-style: italic; } /* Preprocessor */
code > span.ex { } /* Extension */
code > span.at { color: #c4a000; } /* Attribute */
code > span.do { color: #8f5902; font-weight: bold; font-style: italic; } /* Documentation */
code > span.an { color: #8f5902; font-weight: bold; font-style: italic; } /* Annotation */
code > span.cv { color: #8f5902; font-weight: bold; font-style: italic; } /* CommentVar */
code > span.in { color: #8f5902; font-weight: bold; font-style: italic; } /* Information */
</style>
<style type="text/css">
pre:not([class]) {
background-color: white;
}
</style>
<style type="text/css">
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;
}
.table th:not([align]) {
text-align: left;
}
</style>
<link rel="stylesheet" href="style.css" type="text/css" />
</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;
}
.tabbed-pane {
padding-top: 12px;
}
button.code-folding-btn:focus {
outline: none;
}
</style>
<style type="text/css">
/* padding for bootstrap navbar */
body {
padding-top: 51px;
padding-bottom: 40px;
}
/* offset scroll position for anchor links (for fixed navbar) */
.section h1 {
padding-top: 56px;
margin-top: -56px;
}
.section h2 {
padding-top: 56px;
margin-top: -56px;
}
.section h3 {
padding-top: 56px;
margin-top: -56px;
}
.section h4 {
padding-top: 56px;
margin-top: -56px;
}
.section h5 {
padding-top: 56px;
margin-top: -56px;
}
.section h6 {
padding-top: 56px;
margin-top: -56px;
}
</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>
$(document).ready(function () {
window.buildTabsets("TOC");
});
</script>
<!-- code folding -->
<script>
$(document).ready(function () {
// move toc-ignore selectors from section div to header
$('div.section.toc-ignore')
.removeClass('toc-ignore')
.children('h1,h2,h3,h4,h5').addClass('toc-ignore');
// establish options
var options = {
selectors: "h1,h2,h3",
theme: "bootstrap3",
context: '.toc-content',
hashGenerator: function (text) {
return text.replace(/[.\\/?&!#<>]/g, '').replace(/\s/g, '_').toLowerCase();
},
ignoreSelector: ".toc-ignore",
scrollTo: 0
};
options.showAndHide = false;
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.90em;
padding-left: 25px;
text-indent: 0;
}
.tocify .list-group-item {
border-radius: 0px;
}
.tocify-subheader {
display: inline;
}
.tocify-subheader .tocify-item {
font-size: 0.95em;
}
</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="index.html"></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="00-before-we-start.html">Before we start</a>
</li>
<li>
<a href="01-intro-to-R.html">Intro to R</a>
</li>
<li>
<a href="02-starting-with-data.html">Starting with data</a>
</li>
<li>
<a href="03-dplyr.html">Manipulating data frames</a>
</li>
<li>
<a href="04-visualization-ggplot2.html">Visualizing data</a>
</li>
<li>
<a href="05-r-and-databases.html">R and SQL</a>
</li>
<li>
<a href="code-handout.R">Code Handout</a>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li>
<a href="https://github.com/datacarpentry/R-ecology-lesson">
<span class="fa fa-github fa-lg"></span>
</a>
</li>
</ul>
</div><!--/.nav-collapse -->
</div><!--/.container -->
</div><!--/.navbar -->
<div class="fluid-row" id="header">
<h1 class="title toc-ignore">Introduction to R</h1>
<h4 class="author"><em>Data Carpentry contributors</em></h4>
</div>
<hr />
<blockquote>
<h3 id="learning-objectives">Learning Objectives</h3>
<ul>
<li>Define the following terms as they relate to R: script, function, working directory, assign, object, variable.</li>
<li>Call functions with zero or more named or unnamed arguments.</li>
<li>Solve mathematical operations in R.</li>
<li>Assign values to objects and variables in R.</li>
<li>Describe what vectors are and how they are manipulated in R.</li>
<li>Inspect the content of vectors in R and manipulate their content.</li>
<li>Extract values from vectors in R.</li>
<li>Employ logic (i.e. TRUE, FALSE) to subset data in a vector.</li>
<li>Analyze vectors with missing data.</li>
</ul>
</blockquote>
<hr />
<div id="creating-objects" class="section level2">
<h2>Creating objects</h2>
<p>You can get output from R simply by typing in math in the console</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="dv">3</span> +<span class="st"> </span><span class="dv">5</span>
<span class="dv">12</span> /<span class="st"> </span><span class="dv">7</span></code></pre></div>
<p>However, to do useful and interesting things, we need to assign <em>values</em> to <em>objects</em>. To create an object, we need to give it a name followed by the assignment operator <code><-</code>, and the value we want to give it:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">weight_kg <-<span class="st"> </span><span class="dv">55</span></code></pre></div>
<p><code><-</code> is the assignment operator. It assigns values on the right to objects on the left. So, after executing <code>x <- 3</code>, the value of <code>x</code> is <code>3</code>. The arrow can be read as 3 <strong>goes into</strong> <code>x</code>. For historical reasons, you can also use <code>=</code> for assignments, but not in every context. Because of the <a href="http://blog.revolutionanalytics.com/2008/12/use-equals-or-arrow-for-assignment.html">slight</a> <a href="https://web.archive.org/web/20130610005305/https://stat.ethz.ch/pipermail/r-help/2009-March/191462.html">differences</a> in syntax, it is good practice to use always <code><-</code> for assignments.</p>
<p>In RStudio, typing <kbd>Alt</kbd> + <kbd>-</kbd> (push <kbd>Alt</kbd> at the same time as the <kbd>-</kbd> key) will write <code><-</code> in a single keystroke.</p>
<p>Objects can be given any name such as <code>x</code>, <code>current_temperature</code>, or <code>subject_id</code>. You want your object names to be explicit and not too long. They cannot start with a number (<code>2x</code> is not valid, but <code>x2</code> is). R is case sensitive (e.g., <code>weight_kg</code> is different from <code>Weight_kg</code>). There are some names that cannot be used because they are the names of fundamental functions in R (e.g., <code>if</code>, <code>else</code>, <code>for</code>, see <a href="https://stat.ethz.ch/R-manual/R-devel/library/base/html/Reserved.html">here</a> for a complete list). In general, even if it’s allowed, it’s best to not use other function names (e.g., <code>c</code>, <code>T</code>, <code>mean</code>, <code>data</code>, <code>df</code>, <code>weights</code>). If in doubt, check the help to see if the name is already in use. It’s also best to avoid dots (<code>.</code>) within a variable name as in <code>my.dataset</code>. There are many functions in R with dots in their names for historical reasons, but because dots have a special meaning in R (for methods) and other programming languages, it’s best to avoid them. It is also recommended to use nouns for variable names, and verbs for function names. It’s important to be consistent in the styling of your code (where you put spaces, how you name variables, etc.). Using a consistent coding style makes your code clearer to read for your future self and your collaborators. In R, two popular style guides are <a href="http://adv-r.had.co.nz/Style.html">Hadley Wickham’s</a> and <a href="https://google.github.io/styleguide/Rguide.xml">Google’s</a> (this <a href="http://jef.works/R-style-guide/">one</a> is also comprehensive).</p>
<p>When assigning a value to an object, R does not print anything. You can force to print the value by using parentheses or by typing the name:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">weight_kg <-<span class="st"> </span><span class="dv">55</span> <span class="co"># doesn't print anything</span>
(weight_kg <-<span class="st"> </span><span class="dv">55</span>) <span class="co"># but putting parenthesis around the call prints the value of `weight_kg`</span>
weight_kg <span class="co"># and so does typing the name of the object</span></code></pre></div>
<p>Now that R has <code>weight_kg</code> in memory, we can do arithmetic with it. For instance, we may want to convert this weight in pounds (weight in pounds is 2.2 times the weight in kg):</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="fl">2.2</span> *<span class="st"> </span>weight_kg</code></pre></div>
<p>We can also change a variable’s value by assigning it a new one:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">weight_kg <-<span class="st"> </span><span class="fl">57.5</span>
<span class="fl">2.2</span> *<span class="st"> </span>weight_kg</code></pre></div>
<p>This means that assigning a value to one variable does not change the values of other variables. For example, let’s store the animal’s weight in pounds in a new variable, <code>weight_lb</code>:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">weight_lb <-<span class="st"> </span><span class="fl">2.2</span> *<span class="st"> </span>weight_kg</code></pre></div>
<p>and then change <code>weight_kg</code> to 100.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">weight_kg <-<span class="st"> </span><span class="dv">100</span></code></pre></div>
<p>What do you think is the current content of the object <code>weight_lb</code>? 126.5 or 200?</p>
<blockquote>
<h3 id="comments">Comments</h3>
<p>The comment character in R is <code>#</code>, anything to the right of a <code>#</code> in a script will be ignored by R. It is useful to leave notes, and explanations in your scripts. RStudio makes it easy to comment or uncomment a paragraph: after selecting the lines you want to comment, press at the same time on your keyboard <kbd>Crtl</kbd> + <kbd>Shift</kbd> + <kbd>C</kbd>.</p>
</blockquote>
<blockquote>
<h3 id="challenge">Challenge</h3>
<p>What are the values after each statement in the following?</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">mass <-<span class="st"> </span><span class="fl">47.5</span> <span class="co"># mass?</span>
age <-<span class="st"> </span><span class="dv">122</span> <span class="co"># age?</span>
mass <-<span class="st"> </span>mass *<span class="st"> </span><span class="fl">2.0</span> <span class="co"># mass?</span>
age <-<span class="st"> </span>age -<span class="st"> </span><span class="dv">20</span> <span class="co"># age?</span>
mass_index <-<span class="st"> </span>mass/age <span class="co"># mass_index?</span></code></pre></div>
</blockquote>
<div id="functions-and-their-arguments" class="section level3">
<h3>Functions and their arguments</h3>
<p>Functions are “canned scripts” that automate something complicated or convenient or both. Many functions are predefined, or can be made available by importing R <em>packages</em> (more on that later). A function usually gets one or more inputs called <em>arguments</em>. Functions often (but not always) return a <em>value</em>. A typical example would be the function <code>sqrt()</code>. The input (the argument) must be a number, and the return value (in fact, the output) is the square root of that number. Executing a function (‘running it’) is called <em>calling</em> the function. An example of a function call is:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">b <-<span class="st"> </span><span class="kw">sqrt</span>(a)</code></pre></div>
<p>Here, the value of <code>a</code> is given to the <code>sqrt()</code> function, the <code>sqrt()</code> function calculates the square root, and returns the value which is then assigned to variable <code>b</code>. This function is very simple, because it takes just one argument.</p>
<p>The return ‘value’ of a function need not be numerical (like that of <code>sqrt()</code>), and it also does not need to be a single item: it can be a set of things, or even a data set. We’ll see that when we read data files into R.</p>
<p>Arguments can be anything, not only numbers or filenames, but also other objects. Exactly what each argument means differs per function, and must be looked up in the documentation (see below). Some functions take arguments which may either be specified by the user, or, if left out, take on a <em>default</em> value: these are called <em>options</em>. Options are typically used to alter the way the function operates, such as whether it ignores ‘bad values’, or what symbol to use in a plot. However, if you want something specific, you can specify a value of your choice which will be used instead of the default.</p>
<p>Let’s try a function that can take multiple arguments: <code>round()</code>.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">round</span>(<span class="fl">3.14159</span>)</code></pre></div>
<pre><code>#> [1] 3</code></pre>
<p>Here, we’ve called <code>round()</code> with just one argument, <code>3.14159</code>, and it has returned the value <code>3</code>. That’s because the default is to round to the nearest whole number. If we want more digits we can see how to do that by getting information about the <code>round</code> function. We can use <code>args(round)</code> or look at the help for this function using <code>?round</code>.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">args</span>(round)</code></pre></div>
<pre><code>#> function (x, digits = 0)
#> NULL</code></pre>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">?round</code></pre></div>
<p>We see that if we want a different number of digits, we can type <code>digits=2</code> or however many we want.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">round</span>(<span class="fl">3.14159</span>, <span class="dt">digits=</span><span class="dv">2</span>)</code></pre></div>
<pre><code>#> [1] 3.14</code></pre>
<p>If you provide the arguments in the exact same order as they are defined you don’t have to name them:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">round</span>(<span class="fl">3.14159</span>, <span class="dv">2</span>)</code></pre></div>
<pre><code>#> [1] 3.14</code></pre>
<p>And if you do name the arguments, you can switch their order:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">round</span>(<span class="dt">digits=</span><span class="dv">2</span>, <span class="dt">x=</span><span class="fl">3.14159</span>)</code></pre></div>
<pre><code>#> [1] 3.14</code></pre>
<p>It’s good practice to put the non-optional arguments (like the number you’re rounding) first in your function call, and to specify the names of all optional arguments. If you don’t, someone reading your code might have to look up the definition of a function with unfamiliar arguments to understand what you’re doing.</p>
<blockquote>
<h3 id="call-out">Call out</h3>
<p>What is called <code>objects</code> in <code>R</code> is known as <code>variables</code> in many other programming languages. Depending on the context <code>object</code> and <code>variable</code> can have drastically different meanings. However, in this lesson the two words are used synonymously. For more information see: <a href="https://cran.r-project.org/doc/manuals/r-release/R-lang.html#Objects" class="uri">https://cran.r-project.org/doc/manuals/r-release/R-lang.html#Objects</a></p>
</blockquote>
</div>
</div>
<div id="vectors-and-data-types" class="section level2">
<h2>Vectors and data types</h2>
<p>A vector is the most common and basic data structure in R, and is pretty much the workhorse of R. It’s a group of values, mainly either numbers or characters. You can assign this list of values to a variable, just like you would for one item. For example we can create a vector of animal weights:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">weight_g <-<span class="st"> </span><span class="kw">c</span>(<span class="dv">50</span>, <span class="dv">60</span>, <span class="dv">65</span>, <span class="dv">82</span>)
weight_g</code></pre></div>
<p>A vector can also contain characters:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">animals <-<span class="st"> </span><span class="kw">c</span>(<span class="st">"mouse"</span>, <span class="st">"rat"</span>, <span class="st">"dog"</span>)
animals</code></pre></div>
<p>The quotes around “mouse”, “rat”, etc. are essential here. Without the quotes R will assume there is a variable called mouse, rat, etc.</p>
<p>There are many functions that allow you to inspect the content of a vector. <code>length()</code> tells you how many elements are in a particular vector:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">length</span>(weight_g)
<span class="kw">length</span>(animals)</code></pre></div>
<p>An important feature of a vector, is that all of the elements are the same type of data. The function <code>class()</code> indicates the class (the type of element) of an object:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">class</span>(weight_g)
<span class="kw">class</span>(animals)</code></pre></div>
<p>The function <code>str()</code> provides an overview of the object and the elements it contains. It is a really useful function when working with large and complex objects:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">str</span>(weight_g)
<span class="kw">str</span>(animals)</code></pre></div>
<p>You can add elements to your vector by using the <code>c()</code> function:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">weight_g <-<span class="st"> </span><span class="kw">c</span>(weight_g, <span class="dv">90</span>) <span class="co"># adding at the end of the vector</span>
weight_g <-<span class="st"> </span><span class="kw">c</span>(<span class="dv">30</span>, weight_g) <span class="co"># adding at the beginning of the vector</span>
weight_g</code></pre></div>
<p>What happens here is that we take the original vector <code>weight_g</code>, and we are adding another item first to the end of the other ones, and then another item at the beginning. We can do this over and over again to grow a vector, or assemble a dataset. As we program, this may be useful to add results that we are collecting or calculating.</p>
<p>We just saw 2 of the 6 <strong>atomic vector</strong> types that R uses: <code>"character"</code> and <code>"numeric"</code>. These are the basic building blocks that all R objects are built from. The other 4 are:</p>
<ul>
<li><code>"logical"</code> for <code>TRUE</code> and <code>FALSE</code> (the boolean data type)</li>
<li><code>"integer"</code> for integer numbers (e.g., <code>2L</code>, the <code>L</code> indicates to R that it’s an integer)</li>
<li><code>"complex"</code> to represent complex numbers with real and imaginary parts (e.g., <code>1+4i</code>) and that’s all we’re going to say about them</li>
<li><code>"raw"</code> that we won’t discuss further</li>
</ul>
<p>Vectors are one of the many <strong>data structures</strong> that R uses. Other important ones are lists (<code>list</code>), matrices (<code>matrix</code>), data frames (<code>data.frame</code>) and factors (<code>factor</code>).</p>
<blockquote>
<h3 id="challenge-1">Challenge</h3>
<ul>
<li><p>We’ve seen that atomic vectors can be of type character, numeric, integer, and logical. But what happens if we try to mix these types in a single vector? <!-- * _Answer_: R implicitly converts them to all be the same type --></p></li>
<li><p>What will happen in each of these examples? (hint: use <code>class()</code> to check the data type of your objects):</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">num_char <-<span class="st"> </span><span class="kw">c</span>(<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>, <span class="st">'a'</span>)
num_logical <-<span class="st"> </span><span class="kw">c</span>(<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>, <span class="ot">TRUE</span>)
char_logical <-<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="ot">TRUE</span>)
tricky <-<span class="st"> </span><span class="kw">c</span>(<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>, <span class="st">'4'</span>)</code></pre></div></li>
<li><p>Why do you think it happens? <!-- * _Answer_: Vectors can be of only one data type. R tries to convert (coerce)
the content of this vector to find a "common denominator". --></p></li>
</ul>
</blockquote>
<blockquote>
<ul>
<li>You’ve probably noticed that objects of different types get converted into a single, shared type within a vector. In R, we call converting objects from one class into another class <em>coercion</em>. These conversions happen according to a hierarchy, whereby some types get preferentially coerced into other types. Can you draw a diagram that represents the hierarchy of how these data types are coerced? <!-- * _Answer_: `logical -> numeric -> character <-- logical` --></li>
</ul>
</blockquote>
</div>
<div id="subsetting-vectors" class="section level2">
<h2>Subsetting vectors</h2>
<p>If we want to extract one or several values from a vector, we must provide one or several indices in square brackets. For instance:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">animals <-<span class="st"> </span><span class="kw">c</span>(<span class="st">"mouse"</span>, <span class="st">"rat"</span>, <span class="st">"dog"</span>, <span class="st">"cat"</span>)
animals[<span class="dv">2</span>]</code></pre></div>
<pre><code>#> [1] "rat"</code></pre>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">animals[<span class="kw">c</span>(<span class="dv">3</span>, <span class="dv">2</span>)]</code></pre></div>
<pre><code>#> [1] "dog" "rat"</code></pre>
<p>We can also repeat the indices to create an object with more elements than the original one:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">more_animals <-<span class="st"> </span>animals[<span class="kw">c</span>(<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>, <span class="dv">2</span>, <span class="dv">1</span>, <span class="dv">4</span>)]
more_animals</code></pre></div>
<pre><code>#> [1] "mouse" "rat" "dog" "rat" "mouse" "cat"</code></pre>
<p>R indexes start at 1. Programming languages like Fortran, MATLAB, and R start counting at 1, because that’s what human beings typically do. Languages in the C family (including C++, Java, Perl, and Python) count from 0 because that’s simpler for computers to do.</p>
<div id="conditional-subsetting" class="section level3">
<h3>Conditional subsetting</h3>
<p>Another common way of subsetting is by using a logical vector: <code>TRUE</code> will select the element with the same index, while <code>FALSE</code> will not:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">weight_g <-<span class="st"> </span><span class="kw">c</span>(<span class="dv">21</span>, <span class="dv">34</span>, <span class="dv">39</span>, <span class="dv">54</span>, <span class="dv">55</span>)
weight_g[<span class="kw">c</span>(<span class="ot">TRUE</span>, <span class="ot">FALSE</span>, <span class="ot">TRUE</span>, <span class="ot">TRUE</span>, <span class="ot">FALSE</span>)]</code></pre></div>
<pre><code>#> [1] 21 39 54</code></pre>
<p>Typically, these logical vectors are not typed by hand, but are the output of other functions or logical tests. For instance, if you wanted to select only the values above 50:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">weight_g ><span class="st"> </span><span class="dv">50</span> <span class="co"># will return logicals with TRUE for the indices that meet the condition</span></code></pre></div>
<pre><code>#> [1] FALSE FALSE FALSE TRUE TRUE</code></pre>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">## so we can use this to select only the values above 50
weight_g[weight_g ><span class="st"> </span><span class="dv">50</span>]</code></pre></div>
<pre><code>#> [1] 54 55</code></pre>
<p>You can combine multiple tests using <code>&</code> (both conditions are true, AND) or <code>|</code> (at least one of the conditions is true, OR):</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">weight_g[weight_g <<span class="st"> </span><span class="dv">30</span> |<span class="st"> </span>weight_g ><span class="st"> </span><span class="dv">50</span>]</code></pre></div>
<pre><code>#> [1] 21 54 55</code></pre>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">weight_g[weight_g >=<span class="st"> </span><span class="dv">30</span> &<span class="st"> </span>weight_g ==<span class="st"> </span><span class="dv">21</span>]</code></pre></div>
<pre><code>#> numeric(0)</code></pre>
<p>Here, <code><</code> stands for “smaller than”, <code>></code> or “bigger than”, <code>>=</code> for “bigger or equal to”, and <code>==</code> for “equal to”. The double equal sign <code>==</code> should not be confused with the single <code>=</code> sign, which assigns to a variable (roughly speaking the same as “<code><-</code>”).</p>
<p>A common task is to search for certain strings in a vector. One could use the “or” operator <code>|</code> but this can become quickly tedious. The function <code>%in%</code> allows you to test if a value is found in a vector:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">animals <-<span class="st"> </span><span class="kw">c</span>(<span class="st">"mouse"</span>, <span class="st">"rat"</span>, <span class="st">"dog"</span>, <span class="st">"cat"</span>)
animals[animals ==<span class="st"> "cat"</span> |<span class="st"> </span>animals ==<span class="st"> "rat"</span>] <span class="co"># returns both rat and cat</span></code></pre></div>
<pre><code>#> [1] "rat" "cat"</code></pre>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">animals %in%<span class="st"> </span><span class="kw">c</span>(<span class="st">"rat"</span>, <span class="st">"cat"</span>, <span class="st">"dog"</span>, <span class="st">"duck"</span>)</code></pre></div>
<pre><code>#> [1] FALSE TRUE TRUE TRUE</code></pre>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">animals[animals %in%<span class="st"> </span><span class="kw">c</span>(<span class="st">"rat"</span>, <span class="st">"cat"</span>, <span class="st">"dog"</span>, <span class="st">"duck"</span>)]</code></pre></div>
<pre><code>#> [1] "rat" "dog" "cat"</code></pre>
<blockquote>
<h3 id="challenge-optional" class="challenge">Challenge (optional)</h3>
<ul>
<li>Can you figure out why <code>"four" > "five"</code> returns <code>TRUE</code>?</li>
</ul>
</blockquote>
<!--
```r
## Answers
## * When using ">" or "<" on strings, R compares their alphabetical order. Here
## "four" comes after "five", and therefore is "greater than" it.
```
-->
</div>
</div>
<div id="missing-data" class="section level2">
<h2>Missing data</h2>
<p>As R was designed to analyze datasets, it includes the concept of missing data (which is uncommon in other programming languages). Missing data are represented in vectors as <code>NA</code>.</p>
<p>When doing operations on numbers, most functions will return <code>NA</code> if the data you are working with include missing values. This feature makes it harder to overlook the cases where you are dealing with missing data. You can add the argument <code>na.rm=TRUE</code> to calculate the result while ignoring the missing values.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">heights <-<span class="st"> </span><span class="kw">c</span>(<span class="dv">2</span>, <span class="dv">4</span>, <span class="dv">4</span>, <span class="ot">NA</span>, <span class="dv">6</span>)
<span class="kw">mean</span>(heights)
<span class="kw">max</span>(heights)
<span class="kw">mean</span>(heights, <span class="dt">na.rm =</span> <span class="ot">TRUE</span>)
<span class="kw">max</span>(heights, <span class="dt">na.rm =</span> <span class="ot">TRUE</span>)</code></pre></div>
<p>If your data include missing values, you may want to become familiar with the functions <code>is.na()</code>, <code>na.omit()</code>, and <code>complete.cases()</code>. See below for examples.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">## Extract those elements which are not missing values.
heights[!<span class="kw">is.na</span>(heights)]
## Returns the object with incomplete cases removed. The returned object is atomic.
<span class="kw">na.omit</span>(heights)
## Extract those elements which are complete cases.
heights[<span class="kw">complete.cases</span>(heights)]</code></pre></div>
<blockquote>
<h3 id="challenge-2">Challenge</h3>
<ol style="list-style-type: decimal">
<li><p>Using this vector of length measurements, create a new vector with the NAs removed.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">lengths <-<span class="st"> </span><span class="kw">c</span>(<span class="dv">10</span>,<span class="dv">24</span>,<span class="ot">NA</span>,<span class="dv">18</span>,<span class="ot">NA</span>,<span class="dv">20</span>)</code></pre></div></li>
<li><p>Use the function <code>median()</code> to calculate the median of the <code>lengths</code> vector.</p></li>
</ol>
</blockquote>
<p>Now that we have learned how to write scripts, and the basics of R’s data structures, we are ready to start working with the Portal dataset we have been using in the other lessons, and learn about data frames.</p>
</div>
<hr/>
<p><a href="http://datacarpentry.org/">Data Carpentry</a>, 2017. <br/>
<a href="LICENSE.html">License</a>. Questions? Feedback?
Please <a href="https://github.com/datacarpentry/R-ecology-lesson/issues/new">file
an issue on GitHub</a>. <br/>
On Twitter: <a href="https://twitter.com/datacarpentry">@datacarpentry</a></p>
</div>
</div>
</div>
<script>
// add bootstrap table styles to pandoc tables
function bootstrapStylePandocTables() {
$('tr.header').parent('thead').parent('table').addClass('table table-condensed');
}
$(document).ready(function () {
bootstrapStylePandocTables();
});
</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>