forked from datacarpentry/R-ecology-lesson
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path02-starting-with-data.html
707 lines (629 loc) · 33.2 KB
/
02-starting-with-data.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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
<!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>Starting with data</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">Starting with data</h1>
<h4 class="author"><em>Data Carpentry contributors</em></h4>
</div>
<hr />
<blockquote>
<h3 id="learning-objectives">Learning Objectives</h3>
<ul>
<li>Describe what a data frame is.</li>
<li>Load external data from a .csv file into a data frame in R.</li>
<li>Summarize the contents of a data frame in R.</li>
<li>Manipulate categorical data in R.</li>
<li>Change how character strings are handled in a data frame.</li>
</ul>
</blockquote>
<hr />
<div id="presentation-of-the-survey-data" class="section level2">
<h2>Presentation of the Survey Data</h2>
<p>We are studying the species and weight of animals caught in plots in our study area. The dataset is stored as a comma separated value (CSV) file. Each row holds information for a single animal, and the columns represent:</p>
<table>
<thead>
<tr class="header">
<th>Column</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>record_id</td>
<td>Unique id for the observation</td>
</tr>
<tr class="even">
<td>month</td>
<td>month of observation</td>
</tr>
<tr class="odd">
<td>day</td>
<td>day of observation</td>
</tr>
<tr class="even">
<td>year</td>
<td>year of observation</td>
</tr>
<tr class="odd">
<td>plot_id</td>
<td>ID of a particular plot</td>
</tr>
<tr class="even">
<td>species_id</td>
<td>2-letter code</td>
</tr>
<tr class="odd">
<td>sex</td>
<td>sex of animal (“M”, “F”)</td>
</tr>
<tr class="even">
<td>hindfoot_length</td>
<td>length of the hindfoot in mm</td>
</tr>
<tr class="odd">
<td>weight</td>
<td>weight of the animal in grams</td>
</tr>
<tr class="even">
<td>genus</td>
<td>genus of animal</td>
</tr>
<tr class="odd">
<td>species</td>
<td>species of animal</td>
</tr>
<tr class="even">
<td>taxa</td>
<td>e.g. Rodent, Reptile, Bird, Rabbit</td>
</tr>
<tr class="odd">
<td>plot_type</td>
<td>type of plot</td>
</tr>
</tbody>
</table>
<p>We are going to use the R function <code>download.file()</code> to download the CSV file that contains the survey data from figshare, and we will use <code>read.csv()</code> to load into memory the content of the CSV file as an object of class <code>data.frame</code>.</p>
<p>To download the data into the <code>data/</code> subdirectory, run the following:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">download.file</span>(<span class="st">"https://ndownloader.figshare.com/files/2292169"</span>,
<span class="st">"data/portal_data_joined.csv"</span>)</code></pre></div>
<p>You are now ready to load the data:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">surveys <-<span class="st"> </span><span class="kw">read.csv</span>(<span class="st">'data/portal_data_joined.csv'</span>)</code></pre></div>
<p>This statement doesn’t produce any output because, as you might recall, assignments don’t display anything. If we want to check that our data has been loaded, we can print the variable’s value: <code>surveys</code>.</p>
<p>Wow… that was a lot of output. At least it means the data loaded properly. Let’s check the top (the first 6 lines) of this data frame using the function <code>head()</code>:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">head</span>(surveys)</code></pre></div>
<pre><code>#> record_id month day year plot_id species_id sex hindfoot_length weight
#> 1 1 7 16 1977 2 NL M 32 NA
#> 2 72 8 19 1977 2 NL M 31 NA
#> 3 224 9 13 1977 2 NL NA NA
#> 4 266 10 16 1977 2 NL NA NA
#> 5 349 11 12 1977 2 NL NA NA
#> 6 363 11 12 1977 2 NL NA NA
#> genus species taxa plot_type
#> 1 Neotoma albigula Rodent Control
#> 2 Neotoma albigula Rodent Control
#> 3 Neotoma albigula Rodent Control
#> 4 Neotoma albigula Rodent Control
#> 5 Neotoma albigula Rodent Control
#> 6 Neotoma albigula Rodent Control</code></pre>
</div>
<div id="what-are-data-frames" class="section level2">
<h2>What are data frames?</h2>
<p>Data frames are the <em>de facto</em> data structure for most tabular data, and what we use for statistics and plotting.</p>
<p>A data frame can be created by hand, but most commonly they are generated by the functions <code>read.csv()</code> or <code>read.table()</code>; in other words, when importing spreadsheets from your hard drive (or the web).</p>
<p>A <code>data.frame</code> is the representation of data in the format of a table where the columns are vectors that all have the same length. Because the column are vectors, they all contain the same type of data (e.g., characters, integers, factors). We can see this when inspecting the <b>str</b>ucture of a <code>data.frame</code> with the function <code>str()</code>:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">str</span>(surveys)</code></pre></div>
</div>
<div id="inspecting-data.frame-objects" class="section level2">
<h2>Inspecting <code>data.frame</code> Objects</h2>
<p>We already saw how the functions <code>head()</code> and <code>str()</code> can be useful to check the content and the structure of a <code>data.frame</code>. Here is a non-exhaustive list of functions to get a sense of the content/structure of the data. Let’s try them out!</p>
<ul>
<li>Size:
<ul>
<li><code>dim(surveys)</code> - returns a vector with the number of rows in the first element, and the number of columns as the second element (the <strong>dim</strong>ensions of the object)</li>
<li><code>nrow(surveys)</code> - returns the number of rows</li>
<li><code>ncol(surveys)</code> - returns the number of columns</li>
</ul></li>
<li>Content:
<ul>
<li><code>head(surveys)</code> - shows the first 6 rows</li>
<li><code>tail(surveys)</code> - shows the last 6 rows</li>
</ul></li>
<li>Names:
<ul>
<li><code>names(surveys)</code> - returns the column names (synonym of <code>colnames()</code> for <code>data.frame</code> objects)</li>
<li><code>rownames(surveys)</code> - returns the row names</li>
</ul></li>
<li>Summary:
<ul>
<li><code>str(surveys)</code> - structure of the object and information about the class, length and content of each column</li>
<li><code>summary(surveys)</code> - summary statistics for each column</li>
</ul></li>
</ul>
<p>Note: most of these functions are “generic”, they can be used on other types of objects besides <code>data.frame</code>.</p>
<blockquote>
<h3 id="challenge">Challenge</h3>
<p>Based on the output of <code>str(surveys)</code>, can you answer the following questions?</p>
<ul>
<li>What is the class of the object <code>surveys</code>?</li>
<li>How many rows and how many columns are in this object?</li>
<li>How many species have been recorded during these surveys?</li>
</ul>
</blockquote>
<!---
--->
</div>
<div id="indexing-and-subsetting-data-frames" class="section level2">
<h2>Indexing and subsetting data frames</h2>
<p>Our survey data frame has rows and columns (it has 2 dimensions), if we want to extract some specific data from it, we need to specify the “coordinates” we want from it. Row numbers come first, followed by column numbers. However, note that different ways of specifying these coordinates lead to results with different classes.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">surveys[<span class="dv">1</span>] <span class="co"># first column in the data frame (as a data.frame)</span>
surveys[, <span class="dv">1</span>] <span class="co"># first column in the data frame (as a vector)</span>
surveys[<span class="dv">1</span>, <span class="dv">1</span>] <span class="co"># first element in the first column of the data frame (as a vector)</span>
surveys[<span class="dv">1</span>, <span class="dv">6</span>] <span class="co"># first element in the 6th column (as a vector)</span>
surveys[<span class="dv">1</span>:<span class="dv">3</span>, <span class="dv">7</span>] <span class="co"># first three elements in the 7th column (as a vector)</span>
surveys[<span class="dv">3</span>, ] <span class="co"># the 3rd element for all columns (as a data.frame)</span>
head_surveys <-<span class="st"> </span>surveys[<span class="dv">1</span>:<span class="dv">6</span>, ] <span class="co"># equivalent to head(surveys)</span></code></pre></div>
<p><code>:</code> is a special function that creates numeric vectors of integers in increasing or decreasing order, test <code>1:10</code> and <code>10:1</code> for instance.</p>
<p>You can also exclude certain parts of a data frame using the “<code>-</code>” sign:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">surveys[,-<span class="dv">1</span>] <span class="co">#The whole data frame, except the first column</span>
surveys[-<span class="kw">c</span>(<span class="dv">7</span>:<span class="dv">34786</span>),] <span class="co">#equivalent to head(surveys)</span></code></pre></div>
<p>As well as using numeric values to subset a <code>data.frame</code> (or <code>matrix</code>), columns can be called by name, using one of the four following notations:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">surveys[<span class="st">"species_id"</span>] <span class="co"># Result is a data.frame</span>
surveys[, <span class="st">"species_id"</span>] <span class="co"># Result is a vector</span>
surveys[[<span class="st">"species_id"</span>]] <span class="co"># Result is a vector</span>
surveys$species_id <span class="co"># Result is a vector</span></code></pre></div>
<p>For our purposes, the last three notations are equivalent. RStudio knows about the columns in your data frame, so you can take advantage of the autocompetion feature to get the full and correct column name.</p>
<blockquote>
<h3 id="challenge-1">Challenge</h3>
<ol style="list-style-type: decimal">
<li><p>Create a <code>data.frame</code> (<code>surveys_200</code>) containing only the observations from row 200 of the <code>surveys</code> dataset.</p></li>
<li><p>Notice how <code>nrow()</code> gave you the number of rows in a <code>data.frame</code>?</p>
<ul>
<li>Use that number to pull out just that last row in the data frame.</li>
<li>Compare that with what you see as the last row using <code>tail()</code> to make sure it’s meeting expectations.</li>
<li>Pull out that last row using <code>nrow()</code> instead of the row number.</li>
<li>Create a new data frame object (<code>surveys_last</code>) from that last row.</li>
</ul></li>
<li><p>Use <code>nrow()</code> to extract the row that is in the middle of the data frame. Store the content of this row in an object named <code>surveys_middle</code>.</p></li>
<li><p>Combine <code>nrow()</code> with the <code>-</code> notation above to reproduce the behavior of <code>head(surveys)</code> keeping just the first through 6th rows of the surveys dataset.</p></li>
</ol>
</blockquote>
<!---
```r
## Answers
surveys_200 <- surveys[200, ]
surveys_last <- surveys[nrow(surveys), ]
surveys_middle <- surveys[nrow(surveys)/2, ]
surveys_head <- surveys[-c(7:nrow(surveys)),]
```
--->
</div>
<div id="factors" class="section level2">
<h2>Factors</h2>
<p>When we did <code>str(surveys)</code> we saw that several of the columns consist of integers, however, the columns <code>genus</code>, <code>species</code>, <code>sex</code>, <code>plot_type</code>, … are of a special class called a <code>factor</code>. Factors are very useful and are actually something that make R particularly well suited to working with data, so we’re going to spend a little time introducing them.</p>
<p>Factors are used to represent categorical data. Factors can be ordered or unordered, and understanding them is necessary for statistical analysis and for plotting.</p>
<p>Factors are stored as integers, and have labels (text) associated with these unique integers. While factors look (and often behave) like character vectors, they are actually integers under the hood, and you need to be careful when treating them like strings.</p>
<p>Once created, factors can only contain a pre-defined set of values, known as <em>levels</em>. By default, R always sorts <em>levels</em> in alphabetical order. For instance, if you have a factor with 2 levels:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">sex <-<span class="st"> </span><span class="kw">factor</span>(<span class="kw">c</span>(<span class="st">"male"</span>, <span class="st">"female"</span>, <span class="st">"female"</span>, <span class="st">"male"</span>))</code></pre></div>
<p>R will assign <code>1</code> to the level <code>"female"</code> and <code>2</code> to the level <code>"male"</code> (because <code>f</code> comes before <code>m</code>, even though the first element in this vector is <code>"male"</code>). You can check this by using the function <code>levels()</code>, and check the number of levels using <code>nlevels()</code>:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">levels</span>(sex)
<span class="kw">nlevels</span>(sex)</code></pre></div>
<p>Sometimes, the order of the factors does not matter, other times you might want to specify the order because it is meaningful (e.g., “low”, “medium”, “high”), it improves your visualization, or it is required by a particular type of analysis. Here, one way to reorder our levels in the <code>sex</code> vector would be:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">sex <span class="co"># current order</span></code></pre></div>
<pre><code>#> [1] male female female male
#> Levels: female male</code></pre>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">sex <-<span class="st"> </span><span class="kw">factor</span>(sex, <span class="dt">levels =</span> <span class="kw">c</span>(<span class="st">"male"</span>, <span class="st">"female"</span>))
sex <span class="co"># after re-ordering</span></code></pre></div>
<pre><code>#> [1] male female female male
#> Levels: male female</code></pre>
<p>In R’s memory, these factors are represented by integers (1, 2, 3), but are more informative than integers because factors are self describing: <code>"female"</code>, <code>"male"</code> is more descriptive than <code>1</code>, <code>2</code>. Which one is “male”? You wouldn’t be able to tell just from the integer data. Factors, on the other hand, have this information built in. It is particularly helpful when there are many levels (like the species names in our example dataset).</p>
<div id="converting-factors" class="section level3">
<h3>Converting factors</h3>
<p>If you need to convert a factor to a character vector, you use <code>as.character(x)</code>.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">as.character</span>(sex)</code></pre></div>
<p>Converting factors where the levels appear as numbers (such as concentration levels, or years) to a numeric vector is a little trickier. One method is to convert factors to characters and then numbers. Another method is to use the <code>levels()</code> function. Compare:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">f <-<span class="st"> </span><span class="kw">factor</span>(<span class="kw">c</span>(<span class="dv">1990</span>, <span class="dv">1983</span>, <span class="dv">1977</span>, <span class="dv">1998</span>, <span class="dv">1990</span>))
<span class="kw">as.numeric</span>(f) <span class="co"># wrong! and there is no warning...</span>
<span class="kw">as.numeric</span>(<span class="kw">as.character</span>(f)) <span class="co"># works...</span>
<span class="kw">as.numeric</span>(<span class="kw">levels</span>(f))[f] <span class="co"># The recommended way.</span></code></pre></div>
<p>Notice that in the <code>levels()</code> approach, three important steps occur:</p>
<ul>
<li>We obtain all the factor levels using <code>levels(f)</code></li>
<li>We convert these levels to numeric values using <code>as.numeric(levels(f))</code></li>
<li>We then access these numeric values using the underlying integers of the vector <code>f</code> inside the square brackets</li>
</ul>
</div>
<div id="renaming-factors" class="section level3">
<h3>Renaming factors</h3>
<p>When your data is stored as a factor, you can use the <code>plot()</code> function to get a quick glance at the number of observations represented by each factor level. Let’s look at the number of males and females captured over the course of the experiment:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">## bar plot of the number of females and males captured during the experiment:
<span class="kw">plot</span>(surveys$sex)</code></pre></div>
<p><img src="img/R-ecology-unnamed-chunk-21-1.png" width="672" /></p>
<p>In addition to males and females, there are about 1700 individuals for which the sex information hasn’t been recorded. Additionally, for the these individuals, there is no label to indicate that the information is missing. Let’s rename this label to something more meaningful. Before doing that, we’re going to pull out the data on sex and work with that data, so we’re not modifying the working copy of the data frame:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">sex <-<span class="st"> </span>surveys$sex
<span class="kw">head</span>(sex)</code></pre></div>
<pre><code>#> [1] M M
#> Levels: F M</code></pre>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">levels</span>(sex)</code></pre></div>
<pre><code>#> [1] "" "F" "M"</code></pre>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">levels</span>(sex)[<span class="dv">1</span>] <-<span class="st"> "missing"</span>
<span class="kw">levels</span>(sex)</code></pre></div>
<pre><code>#> [1] "missing" "F" "M"</code></pre>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">head</span>(sex)</code></pre></div>
<pre><code>#> [1] M M missing missing missing missing
#> Levels: missing F M</code></pre>
<blockquote>
<h3 id="challenge-2">Challenge</h3>
<ul>
<li>Rename “F” and “M” to “female” and “male” respectively.</li>
<li>Now that we have renamed the factor level to “missing”, can you recreate the barplot such that “missing” is last (after “male”)?</li>
</ul>
</blockquote>
<!---
```r
## Answers
levels(sex)[2:3] <- c("female", "male")
sex <- factor(sex, levels = c("female", "male", "missing"))
plot(sex)
```
<img src="img/R-ecology-correct-order-1.png" width="672" />
--->
</div>
<div id="using-stringsasfactorsfalse" class="section level3">
<h3>Using <code>stringsAsFactors=FALSE</code></h3>
<p>By default, when building or importing a data frame, the columns that contain characters (i.e., text) are coerced (=converted) into the <code>factor</code> data type. Depending on what you want to do with the data, you may want to keep these columns as <code>character</code>. To do so, <code>read.csv()</code> and <code>read.table()</code> have an argument called <code>stringsAsFactors</code> which can be set to <code>FALSE</code>.</p>
<p>In most cases, it’s preferrable to set <code>stringsAsFactors = FALSE</code> when importing your data, and converting as a factor only the columns that require this data type.</p>
<p>Compare the output of <code>str(surveys)</code> when setting <code>stringsAsFactors = TRUE</code> (default) and <code>stringsAsFactors = FALSE</code>:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">## Compare the difference between when the data are being read as
## `factor`, and when they are being read as `character`.
surveys <-<span class="st"> </span><span class="kw">read.csv</span>(<span class="st">"data/portal_data_joined.csv"</span>, <span class="dt">stringsAsFactors =</span> <span class="ot">TRUE</span>)
<span class="kw">str</span>(surveys)
surveys <-<span class="st"> </span><span class="kw">read.csv</span>(<span class="st">"data/portal_data_joined.csv"</span>, <span class="dt">stringsAsFactors =</span> <span class="ot">FALSE</span>)
<span class="kw">str</span>(surveys)
## Convert the column "plot_type" into a factor
surveys$plot_type <-<span class="st"> </span><span class="kw">factor</span>(surveys$plot_type)</code></pre></div>
<blockquote>
<h3 id="challenge-3">Challenge</h3>
<ol style="list-style-type: decimal">
<li><p>We have seen how data frames are created when using the <code>read.csv()</code>, but they can also be created by hand with the <code>data.frame()</code> function. There are a few mistakes in this hand-crafted <code>data.frame</code>, can you spot and fix them? Don’t hesitate to experiment!</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">animal_data <-<span class="st"> </span><span class="kw">data.frame</span>(<span class="dt">animal=</span><span class="kw">c</span>(<span class="st">"dog"</span>, <span class="st">"cat"</span>, <span class="st">"sea cucumber"</span>, <span class="st">"sea urchin"</span>),
<span class="dt">feel=</span><span class="kw">c</span>(<span class="st">"furry"</span>, <span class="st">"squishy"</span>, <span class="st">"spiny"</span>),
<span class="dt">weight=</span><span class="kw">c</span>(<span class="dv">45</span>, <span class="dv">8</span> <span class="fl">1.1</span>, <span class="fl">0.8</span>))</code></pre></div></li>
<li>Can you predict the class for each of the columns in the following example? Check your guesses using <code>str(country_climate)</code>:
<ul>
<li>Are they what you expected? Why? Why not?</li>
<li>What would have been different if we had added <code>stringsAsFactors = FALSE</code> to this call?</li>
<li>What would you need to change to ensure that each column had the accurate data type?</li>
</ul>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">country_climate <-<span class="st"> </span><span class="kw">data.frame</span>(<span class="dt">country=</span><span class="kw">c</span>(<span class="st">"Canada"</span>, <span class="st">"Panama"</span>, <span class="st">"South Africa"</span>, <span class="st">"Australia"</span>),
<span class="dt">climate=</span><span class="kw">c</span>(<span class="st">"cold"</span>, <span class="st">"hot"</span>, <span class="st">"temperate"</span>, <span class="st">"hot/temperate"</span>),
<span class="dt">temperature=</span><span class="kw">c</span>(<span class="dv">10</span>, <span class="dv">30</span>, <span class="dv">18</span>, <span class="st">"15"</span>),
<span class="dt">northern_hemisphere=</span><span class="kw">c</span>(<span class="ot">TRUE</span>, <span class="ot">TRUE</span>, <span class="ot">FALSE</span>, <span class="st">"FALSE"</span>),
<span class="dt">has_kangaroo=</span><span class="kw">c</span>(<span class="ot">FALSE</span>, <span class="ot">FALSE</span>, <span class="ot">FALSE</span>, <span class="dv">1</span>))</code></pre></div></li>
</ol>
<p><!--- Answers
--></p>
</blockquote>
<p>The automatic conversion of data type is sometimes a blessing, sometimes an annoyance. Be aware that it exists, learn the rules, and double check that data you import in R are of the correct type within your data frame. If not, use it to your advantage to detect mistakes that might have been introduced during data entry (a letter in a column that should only contain numbers for instance.).</p>
</div>
</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>