-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path02-starting-with-data.html
792 lines (712 loc) · 40 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
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
<!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%; }
td.lineNumbers { text-align: right; padding-right: 4px; padding-left: 4px; color: #aaaaaa; border-right: 1px solid #aaaaaa; }
td.sourceCode { padding-left: 5px; }
code > span.kw { color: #007020; font-weight: bold; } /* Keyword */
code > span.dt { color: #902000; } /* DataType */
code > span.dv { color: #40a070; } /* DecVal */
code > span.bn { color: #40a070; } /* BaseN */
code > span.fl { color: #40a070; } /* Float */
code > span.ch { color: #4070a0; } /* Char */
code > span.st { color: #4070a0; } /* String */
code > span.co { color: #60a0b0; font-style: italic; } /* Comment */
code > span.ot { color: #007020; } /* Other */
code > span.al { color: #ff0000; font-weight: bold; } /* Alert */
code > span.fu { color: #06287e; } /* Function */
code > span.er { color: #ff0000; font-weight: bold; } /* Error */
code > span.wa { color: #60a0b0; font-weight: bold; font-style: italic; } /* Warning */
code > span.cn { color: #880000; } /* Constant */
code > span.sc { color: #4070a0; } /* SpecialChar */
code > span.vs { color: #4070a0; } /* VerbatimString */
code > span.ss { color: #bb6688; } /* SpecialString */
code > span.im { } /* Import */
code > span.va { color: #19177c; } /* Variable */
code > span.cf { color: #007020; font-weight: bold; } /* ControlFlow */
code > span.op { color: #666666; } /* Operator */
code > span.bu { } /* BuiltIn */
code > span.ex { } /* Extension */
code > span.pp { color: #bc7a00; } /* Preprocessor */
code > span.at { color: #7d9029; } /* Attribute */
code > span.do { color: #ba2121; font-style: italic; } /* Documentation */
code > span.an { color: #60a0b0; font-weight: bold; font-style: italic; } /* Annotation */
code > span.cv { color: #60a0b0; font-weight: bold; font-style: italic; } /* CommentVar */
code > span.in { color: #60a0b0; 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/data-lessons/R-nhcdata-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>
<li>Format dates in R</li>
</ul>
</blockquote>
<hr />
<div id="presentation-of-the-idigbio-data" class="section level2">
<h2>Presentation of the iDigBio data</h2>
<p>We are working with data about specimens from 4 genera in the order rodentia. These specimens are housed in natural history collections in the lower 48 states are are aggregated and served through iDigBio, the US’s natural history museum digitization hub.</p>
<p>The data set was retrieved from the <a href="https://portal.idigbio.org/">iDigBio data portal</a> and the file used for teaching here has been simplified by removing many columns of detailed information. These specimens are from many different collections at institutions like the Museum of Vertebrate Zoology at Berkeley and the Ohio State Museum of Natural History.</p>
<p>Column names are <a href="http://rs.tdwg.org/dwc/terms/">Dawin Core</a> terms which have standardized definitions that you can read about in the specification. There are a few columns that iDigBio has added that are not standard and they are noted. Below is a brief description of the information in this data set:</p>
<table>
<thead>
<tr class="header">
<th align="left">Column</th>
<th align="left">Description</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="left">id</td>
<td align="left">A globally unique identifier for the record</td>
</tr>
<tr class="even">
<td align="left">institutionCode</td>
<td align="left">An identifier for the institution</td>
</tr>
<tr class="odd">
<td align="left">collectionCode</td>
<td align="left">Identifies the collection at an institution</td>
</tr>
<tr class="even">
<td align="left">catalogNumber</td>
<td align="left">Legacy identifier of the speciemen</td>
</tr>
<tr class="odd">
<td align="left">recordedBy</td>
<td align="left">Who collected it</td>
</tr>
<tr class="even">
<td align="left">countryCode</td>
<td align="left">3 letter abbreviation of counrty</td>
</tr>
<tr class="odd">
<td align="left">stateProvince</td>
<td align="left">State where speciemen was collected</td>
</tr>
<tr class="even">
<td align="left">county</td>
<td align="left">County where speciment was collected</td>
</tr>
<tr class="odd">
<td align="left">locality</td>
<td align="left">Textual description of collection location</td>
</tr>
<tr class="even">
<td align="left">decimalLatitude</td>
<td align="left">Latitute and longitude</td>
</tr>
<tr class="odd">
<td align="left">decimalLongitude</td>
<td align="left">Latitute and longitude</td>
</tr>
<tr class="even">
<td align="left">eventDate</td>
<td align="left">When the specimen was collected</td>
</tr>
<tr class="odd">
<td align="left">year</td>
<td align="left">When the specimen was collected</td>
</tr>
<tr class="even">
<td align="left">month</td>
<td align="left">When the specimen was collected</td>
</tr>
<tr class="odd">
<td align="left">day</td>
<td align="left">When the specimen was collected</td>
</tr>
<tr class="even">
<td align="left">genus</td>
<td align="left">Genus</td>
</tr>
<tr class="odd">
<td align="left">specificEpithet</td>
<td align="left">Species</td>
</tr>
<tr class="even">
<td align="left">scientificName</td>
<td align="left">Full textual taxanomic name</td>
</tr>
<tr class="odd">
<td align="left">weight</td>
<td align="left">Weight in grams extracted from text</td>
</tr>
<tr class="even">
<td align="left">length</td>
<td align="left">Length in mm extracted from text</td>
</tr>
<tr class="odd">
<td align="left">sex</td>
<td align="left">Sex extracted from text</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>
<p>FIXME: Data path</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/9582724"</span>,
<span class="st">"data/idigbio_rodents.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">specimens <-<span class="st"> </span><span class="kw">read.csv</span>(<span class="st">"data/idigbio_rodents.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>specimens</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>(specimens)</code></pre></div>
<pre><code>#> uuid institutionCode collectionCode
#> 1 060380ea-7b06-474e-8d2e-b6e4a8c21e1a mvz mammal specimens
#> 2 0fb17a79-a8ce-45b6-b57a-2f640e8cccb6 mvz mammal specimens
#> 3 1a69c8ad-0ac3-4612-9dc0-6867e8b9a218 mvz mammal specimens
#> 4 1a9932b4-beab-4472-bec1-a7e68c4b9e6e mvz mammal specimens
#> 5 1f3b8aea-fbae-46d1-91c8-274924b40c9f mvz mammal specimens
#> 6 203f0531-9b46-403f-ac09-3acab5be977c uam mammal specimens
#> catalogNumber recordedBy
#> 1 219088 collector(s): ana lilia trujano álvarez, eric ghilarducci
#> 2 233524 collector(s): william z. lidicker jr.
#> 3 234346 collector(s): william z. lidicker jr.
#> 4 233951 collector(s): william z. lidicker jr.
#> 5 235290 collector(s): william z. lidicker jr.
#> 6 85106 collector(s): tom manning; preparator(s): amber baxter
#> countryCode stateProvince county decimalLatitude
#> 1 usa california contra costa county 37.76095
#> 2 usa california contra costa county 37.89996
#> 3 usa california contra costa county 37.89996
#> 4 usa california contra costa county 37.89996
#> 5 usa california contra costa county 37.89996
#> 6 usa oregon douglas county 43.27512
#> decimalLongitude eventDate year month day genus
#> 1 -121.8866 2005-11-22T19:00:00.000-05:00 2005 11 22 microtus
#> 2 -122.3617 1959-06-20T20:00:00.000-04:00 1959 6 20 microtus
#> 3 -122.3617 1962-11-21T19:00:00.000-05:00 1962 11 21 microtus
#> 4 -122.3617 1960-07-30T20:00:00.000-04:00 1960 7 30 microtus
#> 5 -122.3617 1964-07-03T20:00:00.000-04:00 1964 7 3 microtus
#> 6 -122.7911 1996-10-22T20:00:00.000-04:00 1996 10 22 myodes
#> specificEpithet scientificName weight length sex
#> 1 californicus microtus californicus californicus 30.5 165 male
#> 2 californicus microtus californicus californicus 22.0 143 female
#> 3 californicus microtus californicus californicus 49.0 187 male
#> 4 californicus microtus californicus californicus 33.0 169 female
#> 5 californicus microtus californicus californicus 29.0 159 female
#> 6 californicus myodes californicus 23.5 141 female</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 data frame 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). For example, here is a figure depicting a data frame comprising of a numeric, a character and a logical vector.</p>
<div class="figure">
<img src="img/data-frame.svg" />
</div>
<p>We can see this when inspecting the <b>str</b>ucture of a data frame with the function <code>str()</code>:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">str</span>(specimens)</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 data frame. 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(specimens)</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(specimens)</code> - returns the number of rows</li>
<li><code>ncol(specimens)</code> - returns the number of columns</li>
</ul></li>
<li>Content:
<ul>
<li><code>head(specimens)</code> - shows the first 6 rows</li>
<li><code>tail(specimens)</code> - shows the last 6 rows</li>
</ul></li>
<li>Names:
<ul>
<li><code>names(specimens)</code> - returns the column names (synonym of <code>colnames()</code> for <code>data.frame</code> objects)</li>
<li><code>rownames(specimens)</code> - returns the row names</li>
</ul></li>
<li>Summary:
<ul>
<li><code>str(specimens)</code> - structure of the object and information about the class, length and content of each column</li>
<li><code>summary(specimens)</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(specimens)</code>, can you answer the following questions?</p>
<ul>
<li>What is the class of the object <code>specimens</code>?</li>
<li>How many rows and how many columns are in this object?</li>
<li>How many genera are represented by these specimens?</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">specimens[<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>
specimens[<span class="dv">1</span>, <span class="dv">6</span>] <span class="co"># first element in the 6th column (as a vector)</span>
specimens[, <span class="dv">1</span>] <span class="co"># first column in the data frame (as a vector)</span>
specimens[<span class="dv">1</span>] <span class="co"># first column in the data frame (as a data.frame)</span>
specimens[<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>
specimens[<span class="dv">3</span>, ] <span class="co"># the 3rd element for all columns (as a data.frame)</span>
head_specimens <-<span class="st"> </span>specimens[<span class="dv">1</span>:<span class="dv">6</span>, ] <span class="co"># equivalent to head(specimens)</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">specimens[,-<span class="dv">1</span>] <span class="co"># The whole data frame, except the first column</span>
specimens[-<span class="kw">c</span>(<span class="dv">7</span>:<span class="dv">10767</span>),] <span class="co"># Equivalent to head(specimens)</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">specimens[<span class="st">"genus"</span>] <span class="co"># Result is a data.frame</span>
specimens[, <span class="st">"genus"</span>] <span class="co"># Result is a vector</span>
specimens[[<span class="st">"genus"</span>]] <span class="co"># Result is a vector</span>
specimens$genus <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 autocompletion 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>specimens_200</code>) containing only the observations from row 200 of the <code>specimens</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>specimens_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>specimens_middle</code>.</p></li>
<li><p>Combine <code>nrow()</code> with the <code>-</code> notation above to reproduce the behavior of <code>head(specimens)</code> keeping just the first through 6th rows of the specimens dataset.</p></li>
</ol>
</blockquote>
<!---
```r
## Answers
specimens_200 <- specimens[200, ]
specimens_last <- specimens[nrow(specimens), ]
specimens_middle <- specimens[nrow(specimens)/2, ]
specimens_head <- specimens[-c(7:nrow(specimens)),]
```
--->
</div>
<div id="factors" class="section level2">
<h2>Factors</h2>
<p>When we did <code>str(specimens)</code> we saw that several of the columns consist of integers, however, the columns <code>genus</code>, <code>county</code>, <code>catalogNumber</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>"amara"</code> and <code>2</code> to the level <code>"omus"</code> (because <code>a</code> comes before <code>o</code>, even though the first element in this vector is <code>"omus"</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 sex 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>(specimens$sex)</code></pre></div>
<p><img src="img/R-nhcdata-unnamed-chunk-21-1.png" width="672" /></p>
<p>In addition to males and females, there are about 1500 individuals for which the sex information hasn’t been recorded. Additionally, for 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>specimens$sex
<span class="kw">head</span>(sex)</code></pre></div>
<pre><code>#> [1] male female male female female female
#> Levels: female male</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] "" "female" "male"</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" "female" "male"</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] male female male female female female
#> Levels: missing female male</code></pre>
<blockquote>
<h3 id="challenge-2">Challenge</h3>
<ul>
<li>Rename “female” and “male” to “F” and “M” 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("F", "M")
sex <- factor(sex, levels = c("F", "M", "missing"))
plot(sex)
```
<img src="img/R-nhcdata-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 preferable 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(specimens)</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`.
specimens <-<span class="st"> </span><span class="kw">read.csv</span>(<span class="st">"data/idigbio_rodents.csv"</span>, <span class="dt">stringsAsFactors =</span> <span class="ot">TRUE</span>)
<span class="kw">str</span>(specimens)
specimens <-<span class="st"> </span><span class="kw">read.csv</span>(<span class="st">"data/idigbio_rodents.csv"</span>, <span class="dt">stringsAsFactors =</span> <span class="ot">FALSE</span>)
<span class="kw">str</span>(specimens)
## Convert the column "genus" into a factor
specimens$genus <-<span class="st"> </span><span class="kw">factor</span>(specimens$genus)</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>
<div id="formatting-dates" class="section level2">
<h2>Formatting Dates</h2>
<p>One of the most common issues that new (and experienced!) R users have is converting date and time information into a variable that is appropriate and usable during analyses. As a reminder from earlier in this lesson, the best practice for dealing with date data is to ensure that each component of your date is stored as a separate variable. Using <code>str()</code>, We can confirm that our data frame has a separate column for day, month, and year, and each contains integer values.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">str</span>(specimens)</code></pre></div>
<p>We’re going to be using the <code>ymd()</code> function from the package <strong><code>lubridate</code></strong>. This function is designed to take a vector representing year, month, and day and convert that information to a POSIXct vector. POSIXct is a class of data recognized by R as being a date or date and time. The argument that the function requires is relatively flexible, but, as a best practice, is a character vector formatted as “YYYY-MM-DD”.</p>
<p>Start by loading the required package:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">library</span>(lubridate)</code></pre></div>
<p>Create a character vector from the <code>year</code>, <code>month</code>, and <code>day</code> columns of <code>specimens</code> using <code>paste()</code>:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">paste</span>(specimens$year, specimens$month, specimens$day, <span class="dt">sep=</span><span class="st">"-"</span>)
<span class="co"># sep indicates the character to use to separate each component</span></code></pre></div>
<p>This character vector can be used as the argument for <code>ymd()</code>:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">ymd</span>(<span class="kw">paste</span>(specimens$year, specimens$month, specimens$day, <span class="dt">sep=</span><span class="st">"-"</span>))</code></pre></div>
<p>The resulting POSIXct vector can be added to <code>specimens</code> as a new column called <code>date</code>:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">specimens$date <-<span class="st"> </span><span class="kw">ymd</span>(<span class="kw">paste</span>(specimens$year, specimens$month, specimens$day, <span class="dt">sep=</span><span class="st">"-"</span>))
<span class="kw">str</span>(specimens) <span class="co"># notice the new column, with 'date' as the class</span></code></pre></div>
<p style="text-align: right; font-size: small;">
Page build on: 2017-10-25 10:36:17
</p>
</div>
<hr/>
<p><a href="http://datacarpentry.org/">Data Carpentry</a>,
2017. <a href="LICENSE.html">License</a>. <a href="CONTRIBUTING.html">Contributing</a>. <br/>
Questions? Feedback?
Please <a href="https://github.com/data-lessons/R-nhcdata-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://mathjax.rstudio.com/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML";
document.getElementsByTagName("head")[0].appendChild(script);
})();
</script>
</body>
</html>