forked from ac812/IntroR
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path02-starting-with-data.html
1179 lines (1085 loc) · 57.1 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
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="generator" content="pandoc" />
<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />
<meta name="author" content="Alexia Cardona" />
<title>Starting with data</title>
<script src="site_libs/header-attrs-2.23/header-attrs.js"></script>
<script src="site_libs/jquery-3.6.0/jquery-3.6.0.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>
<style>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;}
code {color: inherit; background-color: rgba(0, 0, 0, 0.04);}
pre:not([class]) { background-color: white }</style>
<script src="site_libs/jqueryui-1.13.2/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 rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script>
$( function() {
$( ".accordion" ).accordion({
heightStyle: "content",
active: false,
collapsible: true
});
} );
</script>
<script>
<!-- search menu pop-up --->
$(function() {
function slideToggle() {
$("#search-box").toggle("slide", 500);
};
$("#search-icon").on("click", function() {
slideToggle();
});
});
</script>
<style type="text/css">
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
span.underline{text-decoration: underline;}
div.column{display: inline-block; vertical-align: top; width: 50%;}
div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
ul.task-list{list-style: none;}
</style>
<style type="text/css">
code {
white-space: pre;
}
.sourceCode {
overflow: visible;
}
</style>
<style type="text/css" data-origin="pandoc">
pre > code.sourceCode { white-space: pre; position: relative; }
pre > code.sourceCode > span { display: inline-block; line-height: 1.25; }
pre > code.sourceCode > span:empty { height: 1.2em; }
.sourceCode { overflow: visible; }
code.sourceCode > span { color: inherit; text-decoration: inherit; }
div.sourceCode { margin: 1em 0; }
pre.sourceCode { margin: 0; }
@media screen {
div.sourceCode { overflow: auto; }
}
@media print {
pre > code.sourceCode { white-space: pre-wrap; }
pre > code.sourceCode > span { text-indent: -5em; padding-left: 5em; }
}
pre.numberSource code
{ counter-reset: source-line 0; }
pre.numberSource code > span
{ position: relative; left: -4em; counter-increment: source-line; }
pre.numberSource code > span > a:first-child::before
{ content: counter(source-line);
position: relative; left: -1em; text-align: right; vertical-align: baseline;
border: none; display: inline-block;
-webkit-touch-callout: none; -webkit-user-select: none;
-khtml-user-select: none; -moz-user-select: none;
-ms-user-select: none; user-select: none;
padding: 0 4px; width: 4em;
color: #aaaaaa;
}
pre.numberSource { margin-left: 3em; border-left: 1px solid #aaaaaa; padding-left: 4px; }
div.sourceCode
{ }
@media screen {
pre > code.sourceCode > span > a:first-child::before { text-decoration: underline; }
}
code span.al { color: #ff0000; font-weight: bold; } /* Alert */
code span.an { color: #60a0b0; font-weight: bold; font-style: italic; } /* Annotation */
code span.at { color: #7d9029; } /* Attribute */
code span.bn { color: #40a070; } /* BaseN */
code span.bu { color: #008000; } /* BuiltIn */
code span.cf { color: #007020; font-weight: bold; } /* ControlFlow */
code span.ch { color: #4070a0; } /* Char */
code span.cn { color: #880000; } /* Constant */
code span.co { color: #60a0b0; font-style: italic; } /* Comment */
code span.cv { color: #60a0b0; font-weight: bold; font-style: italic; } /* CommentVar */
code span.do { color: #ba2121; font-style: italic; } /* Documentation */
code span.dt { color: #902000; } /* DataType */
code span.dv { color: #40a070; } /* DecVal */
code span.er { color: #ff0000; font-weight: bold; } /* Error */
code span.ex { } /* Extension */
code span.fl { color: #40a070; } /* Float */
code span.fu { color: #06287e; } /* Function */
code span.im { color: #008000; font-weight: bold; } /* Import */
code span.in { color: #60a0b0; font-weight: bold; font-style: italic; } /* Information */
code span.kw { color: #007020; font-weight: bold; } /* Keyword */
code span.op { color: #666666; } /* Operator */
code span.ot { color: #007020; } /* Other */
code span.pp { color: #bc7a00; } /* Preprocessor */
code span.sc { color: #4070a0; } /* SpecialChar */
code span.ss { color: #bb6688; } /* SpecialString */
code span.st { color: #4070a0; } /* String */
code span.va { color: #19177c; } /* Variable */
code span.vs { color: #4070a0; } /* VerbatimString */
code span.wa { color: #60a0b0; font-weight: bold; font-style: italic; } /* Warning */
</style>
<script>
// apply pandoc div.sourceCode style to pre.sourceCode instead
(function() {
var sheets = document.styleSheets;
for (var i = 0; i < sheets.length; i++) {
if (sheets[i].ownerNode.dataset["origin"] !== "pandoc") continue;
try { var rules = sheets[i].cssRules; } catch (e) { continue; }
var j = 0;
while (j < rules.length) {
var rule = rules[j];
// check if there is a div.sourceCode rule
if (rule.type !== rule.STYLE_RULE || rule.selectorText !== "div.sourceCode") {
j++;
continue;
}
var style = rule.style.cssText;
// check if color or background-color is set
if (rule.style.color === '' && rule.style.backgroundColor === '') {
j++;
continue;
}
// replace div.sourceCode by a pre.sourceCode rule
sheets[i].deleteRule(j);
sheets[i].insertRule('pre.sourceCode{' + style + '}', j);
}
}
})();
</script>
<link rel="stylesheet" href="style.css" type="text/css" />
<style type = "text/css">
.main-container {
max-width: 940px;
margin-left: auto;
margin-right: auto;
}
img {
max-width:100%;
}
.tabbed-pane {
padding-top: 12px;
}
.html-widget {
margin-bottom: 20px;
}
button.code-folding-btn:focus {
outline: none;
}
summary {
display: list-item;
}
details > summary > p:only-child {
display: inline;
}
pre code {
padding: 0;
}
</style>
<style type="text/css">
.dropdown-submenu {
position: relative;
}
.dropdown-submenu>.dropdown-menu {
top: 0;
left: 100%;
margin-top: -6px;
margin-left: -1px;
border-radius: 0 6px 6px 6px;
}
.dropdown-submenu:hover>.dropdown-menu {
display: block;
}
.dropdown-submenu>a:after {
display: block;
content: " ";
float: right;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
border-width: 5px 0 5px 5px;
border-left-color: #cccccc;
margin-top: 5px;
margin-right: -10px;
}
.dropdown-submenu:hover>a:after {
border-left-color: #adb5bd;
}
.dropdown-submenu.pull-left {
float: none;
}
.dropdown-submenu.pull-left>.dropdown-menu {
left: -100%;
margin-left: 10px;
border-radius: 6px 0 6px 6px;
}
</style>
<script type="text/javascript">
// 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 the anchor link active (and if it's in a dropdown, also mark that active)
var dropdown = menuAnchor.closest('li.dropdown');
if (window.bootstrap) { // Bootstrap 4+
menuAnchor.addClass('active');
dropdown.find('> .dropdown-toggle').addClass('active');
} else { // Bootstrap 3
menuAnchor.parent().addClass('active');
dropdown.addClass('active');
}
// Navbar adjustments
var navHeight = $(".navbar").first().height() + 15;
var style = document.createElement('style');
var pt = "padding-top: " + navHeight + "px; ";
var mt = "margin-top: -" + navHeight + "px; ";
var css = "";
// offset scroll position for anchor links (for fixed navbar)
for (var i = 1; i <= 6; i++) {
css += ".section h" + i + "{ " + pt + mt + "}\n";
}
style.innerHTML = "body {" + pt + "padding-bottom: 40px; }\n" + css;
document.head.appendChild(style);
});
</script>
<!-- tabsets -->
<style type="text/css">
.tabset-dropdown > .nav-tabs {
display: inline-table;
max-height: 500px;
min-height: 44px;
overflow-y: auto;
border: 1px solid #ddd;
border-radius: 4px;
}
.tabset-dropdown > .nav-tabs > li.active:before, .tabset-dropdown > .nav-tabs.nav-tabs-open:before {
content: "\e259";
font-family: 'Glyphicons Halflings';
display: inline-block;
padding: 10px;
border-right: 1px solid #ddd;
}
.tabset-dropdown > .nav-tabs.nav-tabs-open > li.active:before {
content: "\e258";
font-family: 'Glyphicons Halflings';
border: none;
}
.tabset-dropdown > .nav-tabs > li.active {
display: block;
}
.tabset-dropdown > .nav-tabs > li > a,
.tabset-dropdown > .nav-tabs > li > a:focus,
.tabset-dropdown > .nav-tabs > li > a:hover {
border: none;
display: inline-block;
border-radius: 4px;
background-color: transparent;
}
.tabset-dropdown > .nav-tabs.nav-tabs-open > li {
display: block;
float: none;
}
.tabset-dropdown > .nav-tabs > li {
display: none;
}
</style>
<!-- code folding -->
<style type="text/css">
#TOC {
margin: 25px 0px 20px 0px;
}
@media (max-width: 768px) {
#TOC {
position: relative;
width: 100%;
}
}
@media print {
.toc-content {
/* see https://github.com/w3c/csswg-drafts/issues/4434 */
float: right;
}
}
.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;
}
.tocify .list-group-item {
border-radius: 0px;
}
.tocify-subheader {
display: inline;
}
.tocify-subheader .tocify-item {
font-size: 0.95em;
}
</style>
</head>
<body>
<div class="container-fluid main-container">
<!-- setup 3col/9col grid for toc_float and main content -->
<div class="row">
<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-getting-started.html">Getting started</a>
</li>
<li>
<a href="01-intro-to-r.html">Introduction to R programming</a>
</li>
<li>
<a href="02-starting-with-data.html">Starting with data</a>
</li>
<li>
<a href="03-tidyverse.html">Data manipulation and visualisation</a>
</li>
</ul>
</div><!--/.nav-collapse -->
</div><!--/.container -->
</div><!--/.navbar -->
<div id="header">
<h1 class="title toc-ignore">Starting with data</h1>
<h4 class="author">Alexia Cardona</h4>
</div>
<p><br/></p>
<div id="understanding-data" class="section level2">
<h2>Understanding data</h2>
<p>To be able to do proper data analyses, it is crucial to understand
your data before you can analyse it. So before we start doing any form
of analyses we will first understand the dataset that we will be using
throughout this course. Let us first download the file and have a look
at the data.</p>
<p>We are going to use the R function <code>download.file()</code> to
download the CSV file that contains the data.</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="fu">download.file</span>(<span class="at">url=</span><span class="st">"https://ndownloader.figshare.com/files/2292169"</span>,</span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a> <span class="at">destfile =</span> <span class="st">"data/portal_data_joined.csv"</span>)</span></code></pre></div>
<p>Inside the download.file command, the first entry is a character
string with the source URL (“<a
href="https://ndownloader.figshare.com/files/2292169"
class="uri">https://ndownloader.figshare.com/files/2292169</a>”). This
source URL downloads a CSV file from figshare. The text after the comma
(“data/portal_data_joined.csv”) is the destination of the file on your
local machine.</p>
<p>If you go in the Files section in RStudio, click on the
<code>portal_data_joined.csv</code> file in the <code>data</code> folder
and then click <code>View File</code> you will be able to see the
content of the file.</span></p>
<pre><code>"record_id","month","day","year","plot_id","species_id","sex","hindfoot_length","weight","genus","species","taxa","plot_type"
1,7,16,1977,2,"NL","M","32","","Neotoma","albigula","Rodent","Control"
72,8,19,1977,2,"NL","M","31","","Neotoma","albigula","Rodent","Control" 224,9,13,1977,2,"NL","","","","Neotoma","albigula","Rodent","Control"</code></pre>
<p>From the first 4 lines of the <code>portal_data_joined.csv</code>
file displayed above, we can notice that the file is in the comma
separated value (CSV) format which is a very popular format where
different values are separated by a comma. The first line of the file is
the header of the file which provides a title for each column. In this
dataset, we are studying the species repartition and weight of animals
caught in plots in our study area. The dataset has the following
columns, with each row holding information for a single animal:</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>taxon</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>
</div>
<div id="reading-in-data-from-a-file" class="section level2">
<h2>Reading in data from a file</h2>
<p>Now that we have looked at the raw format of the file (CSV format),
let us load the data into R and look at how data is loaded into R. 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>You are now ready to load the data:</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a>surveys <span class="ot"><-</span> <span class="fu">read.csv</span>(<span class="st">"data/portal_data_joined.csv"</span>)</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 see the contents of the data frame by
typing its name: <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" id="cb4"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a><span class="fu">head</span>(surveys)</span></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 class="sourceCode" id="cb6"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true" tabindex="-1"></a><span class="do">## Try also</span></span>
<span id="cb6-2"><a href="#cb6-2" aria-hidden="true" tabindex="-1"></a><span class="fu">View</span>(surveys)</span></code></pre></div>
<blockquote>
<h4 id="note">Note</h4>
<p><code>read.csv</code> assumes that fields are delineated by commas,
however, in several countries, the comma is used as a decimal separator
and the semicolon (;) is used as a field delineator. If you want to read
in this type of files in R, you can use the <code>read.csv2</code>
function. It behaves exactly like <code>read.csv</code> but uses
different parameters for the decimal and the field separators. If you
are working with another format, they can be both specified by the user.
Check out the help for <code>read.csv()</code> by typing
<code>?read.csv</code> to learn more. There is also the
<code>read.delim()</code> for in tab separated data files. It is
important to note that all of these functions are actually wrapper
functions for the main <code>read.table()</code> function with different
arguments. As such, the surveys data above could have also been loaded
by using <code>read.table()</code> with the separation argument as
<code>,</code>. The code is as follows:
<code>surveys <- read.table(file="data/portal_data_joined.csv", sep=",", header=TRUE)</code>.
The header argument has to be set to TRUE to be able to read the headers
as by default <code>read.table()</code> has the header argument set to
FALSE.</p>
</blockquote>
</div>
<div id="data-frames" class="section level2">
<h2>Data frames</h2>
<p>Data frames are another data structure in R which is most widely used
in the R programming world. It is very popular as most of the data is
readily available in tabular form and it is the also the data structure
used when plotting and performing most analyses in R.</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
columns are vectors, each column must contain a single type of data
(e.g., characters, integers, logical). For example, here is a figure
depicting a data frame comprising a numeric, a character, and a logical
vector.</p>
<p><img src="img/data-frame.svg" /></p>
<p>In R we can see this by inspecting the <b>str</b>ucture of a data
frame with the function <code>str()</code>:</p>
<div class="sourceCode" id="cb7"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb7-1"><a href="#cb7-1" aria-hidden="true" tabindex="-1"></a><span class="fu">str</span>(surveys)</span></code></pre></div>
<pre><code>#> 'data.frame': 34786 obs. of 13 variables:
#> $ record_id : int 1 72 224 266 349 363 435 506 588 661 ...
#> $ month : int 7 8 9 10 11 11 12 1 2 3 ...
#> $ day : int 16 19 13 16 12 12 10 8 18 11 ...
#> $ year : int 1977 1977 1977 1977 1977 1977 1977 1978 1978 1978 ...
#> $ plot_id : int 2 2 2 2 2 2 2 2 2 2 ...
#> $ species_id : chr "NL" "NL" "NL" "NL" ...
#> $ sex : chr "M" "M" "" "" ...
#> $ hindfoot_length: int 32 31 NA NA NA NA NA NA NA NA ...
#> $ weight : int NA NA NA NA NA NA NA NA 218 NA ...
#> $ genus : chr "Neotoma" "Neotoma" "Neotoma" "Neotoma" ...
#> $ species : chr "albigula" "albigula" "albigula" "albigula" ...
#> $ taxa : chr "Rodent" "Rodent" "Rodent" "Rodent" ...
#> $ plot_type : chr "Control" "Control" "Control" "Control" ...</code></pre>
<div id="inspecting-data.frame-objects" class="section level3">
<h3>Inspecting <code>data.frame</code> Objects</h3>
<p>As we mentioned before, it is important to understand your data
before analysing it. Furthermore we want to make sure that the data has
loaded in R properly. To do that, there are several functions we can use
that help us to inspect our data.frame object.</p>
<p>We already saw how the functions <code>head()</code>,
<code>view()</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(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 c 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>
<h4 id="challenge">Challenge</h4>
<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>Which columns are of type <code>character</code>?</li>
</ul>
<div class="accordion">
<h3 class="toc-ignore">
Answer
</h3>
<div style="background: #fff;">
<div class="sourceCode" id="cb9"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb9-1"><a href="#cb9-1" aria-hidden="true" tabindex="-1"></a><span class="fu">str</span>(surveys)</span>
<span id="cb9-2"><a href="#cb9-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb9-3"><a href="#cb9-3" aria-hidden="true" tabindex="-1"></a><span class="do">## * class: data frame</span></span>
<span id="cb9-4"><a href="#cb9-4" aria-hidden="true" tabindex="-1"></a><span class="do">## * how many rows: 34786, how many columns: 13</span></span>
<span id="cb9-5"><a href="#cb9-5" aria-hidden="true" tabindex="-1"></a><span class="do">## * columns of type `character`: species_id, sex, genus, species, taxa, plot_type</span></span></code></pre></div>
</div>
</div>
</blockquote>
</div>
<div id="indexing-and-subsetting-data-frames" class="section level3">
<h3>Indexing and subsetting data frames</h3>
<div id="numeric-indexing" class="section level4">
<h4>Numeric indexing</h4>
<p>You can think of a data frame as a table with rows and columns. Each
element in the data frame can be indexed by the position of the row and
the column in respect to the whole data frame. The index is specified as
[R,C] where R is the position of the row (or row number) and C is the
position of the column (or column number). <strong>Note that
<code>[]</code> are used for indexing, while <code>()</code> are used to
call a function</strong>. Indexing in a data frame starts from 1. To be
able to extract specific data from the surveys data frame, we need to
specify the indices or positions of the elements we want from it. In the
image below we zoom into the first three columns and rows of the surveys
data frame and show their indexes displayed on top of their values in
skyblue.<br />
<img src="img/indexing_dataframe.svg" /></p>
<p>The illustration above illustrates how <strong>numeric
indexing</strong> works. Below are some examples of how we can retrieve
subset of values from the surveys data frame using numeric indexing.</p>
<div class="sourceCode" id="cb10"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb10-1"><a href="#cb10-1" aria-hidden="true" tabindex="-1"></a><span class="co"># get first element in the first column of the data frame</span></span>
<span id="cb10-2"><a href="#cb10-2" aria-hidden="true" tabindex="-1"></a>surveys[<span class="dv">1</span>, <span class="dv">1</span>] </span>
<span id="cb10-3"><a href="#cb10-3" aria-hidden="true" tabindex="-1"></a><span class="co"># get first element in the 6th column</span></span>
<span id="cb10-4"><a href="#cb10-4" aria-hidden="true" tabindex="-1"></a>surveys[<span class="dv">1</span>, <span class="dv">6</span>] </span>
<span id="cb10-5"><a href="#cb10-5" aria-hidden="true" tabindex="-1"></a><span class="co"># get first column of the data frame (as a vector)</span></span>
<span id="cb10-6"><a href="#cb10-6" aria-hidden="true" tabindex="-1"></a>surveys[, <span class="dv">1</span>] </span>
<span id="cb10-7"><a href="#cb10-7" aria-hidden="true" tabindex="-1"></a><span class="co"># get first three elements in the 7th column (as a vector)</span></span>
<span id="cb10-8"><a href="#cb10-8" aria-hidden="true" tabindex="-1"></a>surveys[<span class="dv">1</span><span class="sc">:</span><span class="dv">3</span>, <span class="dv">7</span>] </span>
<span id="cb10-9"><a href="#cb10-9" aria-hidden="true" tabindex="-1"></a><span class="co"># get the 3rd row of the data frame (as a data.frame)</span></span>
<span id="cb10-10"><a href="#cb10-10" aria-hidden="true" tabindex="-1"></a>surveys[<span class="dv">3</span>, ] </span>
<span id="cb10-11"><a href="#cb10-11" aria-hidden="true" tabindex="-1"></a><span class="co"># equivalent to head_surveys <- head(surveys)</span></span>
<span id="cb10-12"><a href="#cb10-12" aria-hidden="true" tabindex="-1"></a>head_surveys <span class="ot"><-</span> surveys[<span class="dv">1</span><span class="sc">:</span><span class="dv">6</span>, ] </span></code></pre></div>
<p><code>:</code> is an operator in R that creates a sequence of numeric
vectors of integers in increasing or decreasing order, test
<code>1:10</code> and <code>10:1</code> for instance. It is equivalent
to the function <code>seq(from, to)</code>.</p>
<p>You can also exclude certain indices of a data frame using the
“<code>-</code>” sign:</p>
<div class="sourceCode" id="cb11"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb11-1"><a href="#cb11-1" aria-hidden="true" tabindex="-1"></a>surveys[, <span class="sc">-</span><span class="dv">1</span>] <span class="co"># get the whole data frame, except the first column</span></span>
<span id="cb11-2"><a href="#cb11-2" aria-hidden="true" tabindex="-1"></a>surveys[<span class="sc">-</span><span class="fu">c</span>(<span class="dv">7</span><span class="sc">:</span><span class="dv">34786</span>), ] <span class="co"># equivalent to head(surveys)</span></span></code></pre></div>
<p><br/></p>
</div>
<div id="name-indexing" class="section level4">
<h4>Name indexing</h4>
<p>Data frames can be subset by calling indices (as shown previously),
but also by calling their row names and column names directly. This is
known as <strong>name indexing</strong>. Below are some example of how
we retrieve data from a data frame using column names.</p>
<div class="sourceCode" id="cb12"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb12-1"><a href="#cb12-1" aria-hidden="true" tabindex="-1"></a><span class="co"># get species_id column as a vector</span></span>
<span id="cb12-2"><a href="#cb12-2" aria-hidden="true" tabindex="-1"></a>surveys[, <span class="st">"species_id"</span>] </span>
<span id="cb12-3"><a href="#cb12-3" aria-hidden="true" tabindex="-1"></a><span class="co"># same as above</span></span>
<span id="cb12-4"><a href="#cb12-4" aria-hidden="true" tabindex="-1"></a>surveys<span class="sc">$</span>species_id </span>
<span id="cb12-5"><a href="#cb12-5" aria-hidden="true" tabindex="-1"></a><span class="co"># get the record_id and species columns for the first three rows</span></span>
<span id="cb12-6"><a href="#cb12-6" aria-hidden="true" tabindex="-1"></a><span class="co"># Note: we are mixing numeric and name indexing here</span></span>
<span id="cb12-7"><a href="#cb12-7" aria-hidden="true" tabindex="-1"></a>surveys[<span class="dv">1</span><span class="sc">:</span><span class="dv">3</span>, <span class="fu">c</span>(<span class="st">"record_id"</span>, <span class="st">"species"</span>)] </span></code></pre></div>
<p>In RStudio, you can use the autocompletion feature to get the full
and correct names of the columns.</p>
<p><br/></p>
</div>
<div id="logical-indexing" class="section level4">
<h4>Logical indexing</h4>
<p>Another way to retrieve data from a data frame is by <strong>logical
indexing</strong>, or in other words, by performing a logical operation
on a data frame.</p>
<div class="sourceCode" id="cb13"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb13-1"><a href="#cb13-1" aria-hidden="true" tabindex="-1"></a><span class="co"># get all the records that have species as "albigula"</span></span>
<span id="cb13-2"><a href="#cb13-2" aria-hidden="true" tabindex="-1"></a>surveys[surveys<span class="sc">$</span>species <span class="sc">==</span> <span class="st">"albigula"</span>,]</span>
<span id="cb13-3"><a href="#cb13-3" aria-hidden="true" tabindex="-1"></a><span class="co"># save all the records that have species as "albigula" into a variable</span></span>
<span id="cb13-4"><a href="#cb13-4" aria-hidden="true" tabindex="-1"></a>albigula_data <span class="ot"><-</span> surveys[surveys<span class="sc">$</span>species <span class="sc">==</span> <span class="st">"albigula"</span>,]</span>
<span id="cb13-5"><a href="#cb13-5" aria-hidden="true" tabindex="-1"></a><span class="co"># how many records have species as "albigula" in the surveys data frame?</span></span>
<span id="cb13-6"><a href="#cb13-6" aria-hidden="true" tabindex="-1"></a><span class="fu">nrow</span>(albigula_data)</span></code></pre></div>
<p>In case you are wondering what a <em>Neotoma albigula</em> is: <a
href="https://commons.wikimedia.org/wiki/File:White-throated_woodrat.jpg"><img
src="https://upload.wikimedia.org/wikipedia/commons/f/f9/White-throated_woodrat.jpg"
alt="Wikipedia" /></a></p>
<p><br/></p>
<blockquote>
<h4 id="challenge-1">Challenge</h4>
<ol style="list-style-type: decimal">
<li><p>Create a <code>data.frame</code> (<code>surveys_200</code>)
containing only the data in 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 (<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>
<div class="accordion">
<h3 class="toc-ignore">
Answer
</h3>
<div style="background: #fff;">
<div class="sourceCode" id="cb14"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb14-1"><a href="#cb14-1" aria-hidden="true" tabindex="-1"></a><span class="do">## 1.</span></span>
<span id="cb14-2"><a href="#cb14-2" aria-hidden="true" tabindex="-1"></a>surveys_200 <span class="ot"><-</span> surveys[<span class="dv">200</span>, ]</span>
<span id="cb14-3"><a href="#cb14-3" aria-hidden="true" tabindex="-1"></a><span class="do">## 2.</span></span>
<span id="cb14-4"><a href="#cb14-4" aria-hidden="true" tabindex="-1"></a><span class="co"># Saving `n_rows` to improve readability and reduce duplication</span></span>
<span id="cb14-5"><a href="#cb14-5" aria-hidden="true" tabindex="-1"></a>n_rows <span class="ot"><-</span> <span class="fu">nrow</span>(surveys)</span>
<span id="cb14-6"><a href="#cb14-6" aria-hidden="true" tabindex="-1"></a>surveys_last <span class="ot"><-</span> surveys[n_rows, ]</span>
<span id="cb14-7"><a href="#cb14-7" aria-hidden="true" tabindex="-1"></a><span class="do">## 3.</span></span>
<span id="cb14-8"><a href="#cb14-8" aria-hidden="true" tabindex="-1"></a>surveys_middle <span class="ot"><-</span> surveys[n_rows <span class="sc">/</span> <span class="dv">2</span>, ]</span>
<span id="cb14-9"><a href="#cb14-9" aria-hidden="true" tabindex="-1"></a><span class="do">## 4.</span></span>
<span id="cb14-10"><a href="#cb14-10" aria-hidden="true" tabindex="-1"></a>surveys_head <span class="ot"><-</span> surveys[<span class="sc">-</span>(<span class="dv">7</span><span class="sc">:</span>n_rows), ]</span></code></pre></div>
</div>
</div>
</blockquote>
</div>
</div>
</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. The columns <code>genus</code>,
<code>species</code>, <code>sex</code>, <code>plot_type</code>, …
however, are of the class <code>character</code>. Arguably, these
columns contain categorical data, that is, they can only take on a
limited number of values.</p>
<p>R has a special class for working with categorical data, called
<code>factor</code>. Factors are very useful and actually contribute to
making R particularly well suited to working with data. So we are going
to spend a little time introducing them.</p>
<p>Once created, factors can only contain a pre-defined set of values,
known as <em>levels</em>. Factors are stored as integers associated with
labels and they can be ordered or unordered. While factors look (and
often behave) like character vectors, they are actually treated as
integer vectors by R. So you need to be very careful when treating them
as strings.</p>
<p>We can convert these columns that contain categorical data to type
factor by using the <code>factor()</code> function:</p>
<div class="sourceCode" id="cb15"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb15-1"><a href="#cb15-1" aria-hidden="true" tabindex="-1"></a>surveys<span class="sc">$</span>sex <span class="ot"><-</span> <span class="fu">factor</span>(surveys<span class="sc">$</span>sex)</span></code></pre></div>
<p>We can see that the conversion has worked by using the
<code>summary()</code> function again. This produces a table with the
counts for each factor level:</p>
<div class="sourceCode" id="cb16"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb16-1"><a href="#cb16-1" aria-hidden="true" tabindex="-1"></a><span class="fu">summary</span>(surveys<span class="sc">$</span>sex)</span></code></pre></div>
<p>By default, R always sorts levels in alphabetical order. For
instance, if you have a factor with 2 levels:</p>
<div class="sourceCode" id="cb17"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb17-1"><a href="#cb17-1" aria-hidden="true" tabindex="-1"></a>sex <span class="ot"><-</span> <span class="fu">factor</span>(<span class="fu">c</span>(<span class="st">"male"</span>, <span class="st">"female"</span>, <span class="st">"female"</span>, <span class="st">"male"</span>))</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 see this by using the function
<code>levels()</code> and you can find the number of levels using
<code>nlevels()</code>:</p>
<div class="sourceCode" id="cb18"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb18-1"><a href="#cb18-1" aria-hidden="true" tabindex="-1"></a><span class="fu">levels</span>(sex)</span>
<span id="cb18-2"><a href="#cb18-2" aria-hidden="true" tabindex="-1"></a><span class="fu">nlevels</span>(sex)</span></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" id="cb19"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb19-1"><a href="#cb19-1" aria-hidden="true" tabindex="-1"></a>sex <span class="co"># current order</span></span></code></pre></div>
<pre><code>#> [1] male female female male
#> Levels: female male</code></pre>
<div class="sourceCode" id="cb21"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb21-1"><a href="#cb21-1" aria-hidden="true" tabindex="-1"></a>sex <span class="ot"><-</span> <span class="fu">factor</span>(sex, <span class="at">levels =</span> <span class="fu">c</span>(<span class="st">"male"</span>, <span class="st">"female"</span>))</span>
<span id="cb21-2"><a href="#cb21-2" aria-hidden="true" tabindex="-1"></a>sex <span class="co"># after re-ordering</span></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>
<blockquote>
<h3 id="challenge-2">Challenge</h3>
<ol style="list-style-type: decimal">
<li><p>Change the columns <code>taxa</code> and <code>genus</code> in
the <code>surveys</code> data frame into a factor.</p></li>
<li><p>Using the functions you learned before, can you find out…</p>
<ul>
<li>How many rabbits were observed?</li>
<li>How many different genera are in the <code>genus</code> column?</li>
</ul></li>
</ol>
<div class="accordion">
<h3 class="toc-ignore">
Answer
</h3>
<div style="background: #fff;">
<div class="sourceCode" id="cb23"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb23-1"><a href="#cb23-1" aria-hidden="true" tabindex="-1"></a>surveys<span class="sc">$</span>genus <span class="ot"><-</span> <span class="fu">factor</span>(surveys<span class="sc">$</span>genus)</span>
<span id="cb23-2"><a href="#cb23-2" aria-hidden="true" tabindex="-1"></a><span class="fu">summary</span>(surveys)</span>
<span id="cb23-3"><a href="#cb23-3" aria-hidden="true" tabindex="-1"></a><span class="fu">nlevels</span>(surveys<span class="sc">$</span>genus)</span>
<span id="cb23-4"><a href="#cb23-4" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb23-5"><a href="#cb23-5" aria-hidden="true" tabindex="-1"></a><span class="do">## * how many genera: There are 26 unique genera in the `genus` column.</span></span>
<span id="cb23-6"><a href="#cb23-6" aria-hidden="true" tabindex="-1"></a><span class="do">## * how many rabbits: There are 75 rabbits in the `taxa` column.</span></span></code></pre></div>
</div>
</div>
</blockquote>
<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" id="cb24"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb24-1"><a href="#cb24-1" aria-hidden="true" tabindex="-1"></a><span class="fu">as.character</span>(sex)</span></code></pre></div>
<p>In some cases, you may have to convert factors where the levels
appear as numbers (such as concentration levels or years) to a numeric
vector. For instance, in one part of your analysis the years might need
to be encoded as factors (e.g., comparing average weights across years)
but in another part of your analysis they may need to be stored as
numeric values (e.g., doing math operations on the years). This
conversion from factor to numeric is a little trickier. The
<code>as.numeric()</code> function returns the index values of the
factor, not its levels, so it will result in an entirely new (and
unwanted in this case) set of numbers. One method to avoid this is to
convert factors to characters, and then to numbers.</p>
<p>Another method is to use the <code>levels()</code> function.
Compare:</p>
<div class="sourceCode" id="cb25"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb25-1"><a href="#cb25-1" aria-hidden="true" tabindex="-1"></a>year_fct <span class="ot"><-</span> <span class="fu">factor</span>(<span class="fu">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>
<span id="cb25-2"><a href="#cb25-2" aria-hidden="true" tabindex="-1"></a><span class="fu">as.numeric</span>(year_fct) <span class="co"># Wrong! And there is no warning...</span></span>
<span id="cb25-3"><a href="#cb25-3" aria-hidden="true" tabindex="-1"></a><span class="fu">as.numeric</span>(<span class="fu">as.character</span>(year_fct)) <span class="co"># Works...</span></span>
<span id="cb25-4"><a href="#cb25-4" aria-hidden="true" tabindex="-1"></a><span class="fu">as.numeric</span>(<span class="fu">levels</span>(year_fct))[year_fct] <span class="co"># The recommended way.</span></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(year_fct)</code></li>
<li>We convert these levels to numeric values using
<code>as.numeric(levels(year_fct))</code></li>
<li>We then access these numeric values using the underlying integers of
the vector <code>year_fct</code> inside the square brackets</li>
</ul>
<p></br></p>
</div>
</div>
<div id="optional-sections" class="section level2">
<h2>Optional sections</h2>
<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" id="cb26"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb26-1"><a href="#cb26-1" aria-hidden="true" tabindex="-1"></a><span class="do">## bar plot of the number of females and males captured during the experiment:</span></span>
<span id="cb26-2"><a href="#cb26-2" aria-hidden="true" tabindex="-1"></a><span class="fu">plot</span>(surveys<span class="sc">$</span>sex)</span></code></pre></div>
<p><img src="img/R-ecology-unnamed-chunk-24-1.png" width="672" /></p>
<p>However, as we saw when we used <code>summary(surveys$sex)</code>,
there are about 1700 individuals for which the sex information hasn’t
been recorded. To show them in the plot, we can turn the missing values
into a factor level. We will also have to give the new factor level a
label. We are going to work with a copy of the <code>sex</code> column,
so we’re not modifying the working copy of the data frame:</p>
<div class="sourceCode" id="cb27"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb27-1"><a href="#cb27-1" aria-hidden="true" tabindex="-1"></a>sex <span class="ot"><-</span> <span class="fu">as.factor</span>(surveys<span class="sc">$</span>sex)</span>
<span id="cb27-2"><a href="#cb27-2" aria-hidden="true" tabindex="-1"></a><span class="fu">head</span>(sex)</span></code></pre></div>
<pre><code>#> [1] M M
#> Levels: F M</code></pre>
<div class="sourceCode" id="cb29"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb29-1"><a href="#cb29-1" aria-hidden="true" tabindex="-1"></a><span class="fu">levels</span>(sex)</span></code></pre></div>
<pre><code>#> [1] "" "F" "M"</code></pre>
<div class="sourceCode" id="cb31"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb31-1"><a href="#cb31-1" aria-hidden="true" tabindex="-1"></a><span class="fu">levels</span>(sex)[<span class="dv">1</span>] <span class="ot"><-</span> <span class="st">"undetermined"</span></span>
<span id="cb31-2"><a href="#cb31-2" aria-hidden="true" tabindex="-1"></a><span class="fu">levels</span>(sex)</span></code></pre></div>
<pre><code>#> [1] "undetermined" "F" "M"</code></pre>
<div class="sourceCode" id="cb33"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb33-1"><a href="#cb33-1" aria-hidden="true" tabindex="-1"></a><span class="fu">head</span>(sex)</span></code></pre></div>
<pre><code>#> [1] M M undetermined undetermined undetermined
#> [6] undetermined
#> Levels: undetermined F M</code></pre>
<p>Now we can plot the data again, using <code>plot(sex)</code>.</p>
<p><img src="img/R-ecology-unnamed-chunk-26-1.png" width="672" /></p>
<blockquote>
<h3 id="challenge-3">Challenge</h3>
<ul>
<li>Rename “F” and “M” to “female” and “male” respectively.</li>
<li>Now that we have renamed the factor level to “undetermined”, can you
recreate the barplot such that “undetermined” is last (after
“male”)?</li>
</ul>
<div class="accordion">
<h3 class="toc-ignore">