forked from datacarpentry/R-ecology-lesson
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path01-intro-to-R.html
374 lines (330 loc) · 25.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
<!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="libs/jquery-1.11.3/jquery.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="libs/bootstrap-3.3.5/css/bootstrap.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>
<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>
</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>
<div class="container-fluid main-container">
<!-- tabsets -->
<script src="libs/navigation-1.1/tabsets.js"></script>
<script>
$(document).ready(function () {
window.buildTabsets("TOC");
});
</script>
<!-- code folding -->
<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>
<div id="TOC">
<ul>
<li><a href="#creating-objects">Creating objects</a><ul>
<li><a href="#challenge">Challenge</a></li>
</ul></li>
<li><a href="#vectors-and-data-types">Vectors and data types</a><ul>
<li><a href="#challenge-1">Challenge</a></li>
</ul></li>
<li><a href="#subsetting-vectors">Subsetting vectors</a><ul>
<li><a href="#conditional-subsetting">Conditional subsetting</a></li>
</ul></li>
<li><a href="#missing-data">Missing data</a><ul>
<li><a href="#challenge-3">Challenge</a></li>
</ul></li>
</ul>
</div>
<hr />
<blockquote>
<h2 id="learning-objectives">Learning Objectives</h2>
<ul>
<li>Familiarize participants with R syntax</li>
<li>Understand the concepts of objects and assignment</li>
<li>Understand the concepts of vector and data types</li>
<li>Get exposed to a few functions</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="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>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>). 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 variable, etc.). 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-styleguide.googlecode.com/svn/trunk/Rguide.xml">Google’s</a>.</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>
<div id="challenge" class="section level3">
<h3>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>
</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>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>
<div id="challenge-1" class="section level3">
<h3>Challenge</h3>
<ul>
<li><p><strong>Question</strong>: 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><strong>Question</strong>: What will happen in each of these examples? (hint: use <code>class()</code> to check the data type of your objects):</p></li>
</ul>
<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>
<ul>
<li><p><strong>Question</strong>: 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>
<li><p><strong>Question</strong>: Can you draw a diagram that represents the hierarchy of the data types? <!-- * _Answer_: `logical -> numeric -> character <-- logical` --></p></li>
</ul>
</div>
</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>When working with vectors of characters, if you are trying to combine many conditions it can become tedious to type. 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-2" class="challenge">Challenge</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>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">planets <-<span class="st"> </span><span class="kw">c</span>(<span class="st">"Mercury"</span>, <span class="st">"Venus"</span>, <span class="st">"Earth"</span>, <span class="st">"Mars"</span>, <span class="st">"Jupiter"</span>, <span class="st">"Saturn"</span>, <span class="st">"Uranus"</span>,
<span class="st">"Neptune"</span>, <span class="ot">NA</span>)</code></pre></div>
<p>When doing operations on numbers, most functions will return <code>NA</code> if the data you are working with include missing values. It is a safer behavior as otherwise you may overlook that 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>
<div id="challenge-3" class="section level3">
<h3>Challenge</h3>
<ul>
<li><strong>Question</strong>: Why does the following piece of code give an error message?</li>
</ul>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">sample <-<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="st">"NA"</span>, <span class="dv">6</span>)
<span class="kw">mean</span>(sample, <span class="dt">na.rm =</span> <span class="ot">TRUE</span>)</code></pre></div>
<pre><code>#> Warning in mean.default(sample, na.rm = TRUE): argument is not numeric or
#> logical: returning NA</code></pre>
<!-- * _Answer_: Because R recognizes the NA in quotes as a character. -->
<ul>
<li><strong>Question</strong>: Why does the error message say the argument is not numeric? <!-- * _Answer_: R converts the entire vector to character because of the "NA", and doesn't recognize it as numeric. --></li>
</ul>
<p>Next, we will use the “surveys” dataset to explore the <code>data.frame</code> data structure, which is one of the most common types of R objects.</p>
</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>