forked from ac812/IntroR
-
Notifications
You must be signed in to change notification settings - Fork 4
/
01-intro-to-r.html
976 lines (882 loc) · 51.3 KB
/
01-intro-to-r.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
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
<!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="Data Carpentry contributors" />
<title>Introduction to R</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">Introduction to R</h1>
<h4 class="author">Data Carpentry contributors</h4>
</div>
<p><br/></p>
<div id="creating-objects-in-r" class="section level2">
<h2>Creating objects in R</h2>
<p>You can get output from R simply by typing math in the console:</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="dv">3</span> <span class="sc">+</span> <span class="dv">5</span></span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a><span class="dv">12</span> <span class="sc">/</span> <span class="dv">7</span></span></code></pre></div>
<p>However, to do useful and interesting things, we need to assign
<em>values</em> to <em>objects</em>. To create an object, we need to
give it a name followed by the assignment operator <code><-</code>,
and the value we want to give it:</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a>weight_kg <span class="ot"><-</span> <span class="dv">55</span></span></code></pre></div>
<p><code><-</code> is the assignment operator. It assigns values on
the right to objects on the left. So, after executing
<code>x <- 3</code>, the value of <code>x</code> is <code>3</code>.
The arrow can be read as 3 <strong>goes into</strong> <code>x</code>.
For historical reasons, you can also use <code>=</code> for assignments,
but not in every context. Because of the <a
href="http://blog.revolutionanalytics.com/2008/12/use-equals-or-arrow-for-assignment.html">slight</a>
<a
href="http://r.789695.n4.nabble.com/Is-there-any-difference-between-and-tp878594p878598.html">differences</a>
in syntax, it is good practice to always use <code><-</code> for
assignments.</p>
<p>In RStudio, typing <kbd>Alt</kbd> + <kbd>-</kbd> (push <kbd>Alt</kbd>
at the same time as the <kbd>-</kbd> key) will write <code><-</code>
in a single keystroke in a PC, while typing <kbd>Option</kbd> +
<kbd>-</kbd> (push <kbd>Option</kbd> at the same time as the
<kbd>-</kbd> key) does the same in a Mac.</p>
<p>Objects can be given any name such as <code>x</code>,
<code>current_temperature</code>, or <code>subject_id</code>. You want
your object names to be explicit and not too long. They cannot start
with a number (<code>2x</code> is not valid, but <code>x2</code> is). R
is case sensitive (e.g., <code>weight_kg</code> is different from
<code>Weight_kg</code>). There are some names that cannot be used
because they are the names of fundamental functions in R (e.g.,
<code>if</code>, <code>else</code>, <code>for</code>, see <a
href="https://stat.ethz.ch/R-manual/R-devel/library/base/html/Reserved.html">here</a>
for a complete list). In general, even if it’s allowed, it’s best to not
use other function names (e.g., <code>c</code>, <code>T</code>,
<code>mean</code>, <code>data</code>, <code>df</code>,
<code>weights</code>). If in doubt, check the help to see if the name is
already in use. It’s also best to avoid dots (<code>.</code>) within an
object name as in <code>my.dataset</code>. There are many functions in R
with dots in their names for historical reasons, but because dots have a
special meaning in R (for methods) and other programming languages, it’s
best to avoid them. It is also recommended to use nouns for object
names, and verbs for function names. It’s important to be consistent in
the styling of your code (where you put spaces, how you name objects,
etc.). Using a consistent coding style makes your code clearer to read
for your future self and your collaborators. In R, three popular style
guides are <a
href="https://google.github.io/styleguide/Rguide.xml">Google’s</a>, <a
href="http://jef.works/R-style-guide/">Jean Fan’s</a> and the <a
href="http://style.tidyverse.org/">tidyverse’s</a>. The tidyverse’s is
very comprehensive and may seem overwhelming at first. You can install
the <a
href="https://github.com/jimhester/lintr"><strong><code>lintr</code></strong></a>
package to automatically check for issues in the styling of your
code.</p>
<blockquote>
<h3 id="objects-vs.-variables">Objects vs. variables</h3>
<p>What are known as <code>objects</code> in <code>R</code> are known as
<code>variables</code> in many other programming languages. Depending on
the context, <code>object</code> and <code>variable</code> can have
drastically different meanings. However, in this lesson, the two words
are used synonymously. For more information see: <a
href="https://cran.r-project.org/doc/manuals/r-release/R-lang.html#Objects"
class="uri">https://cran.r-project.org/doc/manuals/r-release/R-lang.html#Objects</a></p>
</blockquote>
<p>When assigning a value to an object, R does not print anything. You
can force R to print the value by using parentheses or by typing the
object name:</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>weight_kg <span class="ot"><-</span> <span class="dv">55</span> <span class="co"># doesn't print anything</span></span>
<span id="cb3-2"><a href="#cb3-2" aria-hidden="true" tabindex="-1"></a>(weight_kg <span class="ot"><-</span> <span class="dv">55</span>) <span class="co"># but putting parenthesis around the call prints the value of `weight_kg`</span></span>
<span id="cb3-3"><a href="#cb3-3" aria-hidden="true" tabindex="-1"></a>weight_kg <span class="co"># and so does typing the name of the object</span></span></code></pre></div>
<p>Now that R has <code>weight_kg</code> in memory, we can do arithmetic
with it. For instance, we may want to convert this weight into pounds
(weight in pounds is 2.2 times the weight in kg):</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="fl">2.2</span> <span class="sc">*</span> weight_kg</span></code></pre></div>
<p>We can also change an object’s value by assigning it a new one:</p>
<div class="sourceCode" id="cb5"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb5-1"><a href="#cb5-1" aria-hidden="true" tabindex="-1"></a>weight_kg <span class="ot"><-</span> <span class="fl">57.5</span></span>
<span id="cb5-2"><a href="#cb5-2" aria-hidden="true" tabindex="-1"></a><span class="fl">2.2</span> <span class="sc">*</span> weight_kg</span></code></pre></div>
<p>This means that assigning a value to one object does not change the
values of other objects For example, let’s store the animal’s weight in
pounds in a new object, <code>weight_lb</code>:</p>
<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>weight_lb <span class="ot"><-</span> <span class="fl">2.2</span> <span class="sc">*</span> weight_kg</span></code></pre></div>
<p>and then change <code>weight_kg</code> to 100.</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>weight_kg <span class="ot"><-</span> <span class="dv">100</span></span></code></pre></div>
<p>What do you think is the current content of the object
<code>weight_lb</code>? 126.5 or 220?</p>
<div id="comments" class="section level3">
<h3>Comments</h3>
<p>The comment character in R is <code>#</code>, anything to the right
of a <code>#</code> in a script will be ignored by R. It is useful to
leave notes and explanations in your scripts. RStudio makes it easy to
comment or uncomment a paragraph: after selecting the lines you want to
comment, press at the same time on your keyboard <kbd>Ctrl</kbd> +
<kbd>Shift</kbd> + <kbd>C</kbd>. If you only want to comment out one
line, you can put the cursor at any location of that line (i.e. no need
to select the whole line), then press <kbd>Ctrl</kbd> + <kbd>Shift</kbd>
+ <kbd>C</kbd>.</p>
<blockquote>
<h3 id="challenge">Challenge</h3>
<p>What are the values after each statement in the following?</p>
<div class="sourceCode" id="cb8"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true" tabindex="-1"></a>mass <span class="ot"><-</span> <span class="fl">47.5</span> <span class="co"># mass?</span></span>
<span id="cb8-2"><a href="#cb8-2" aria-hidden="true" tabindex="-1"></a>age <span class="ot"><-</span> <span class="dv">122</span> <span class="co"># age?</span></span>
<span id="cb8-3"><a href="#cb8-3" aria-hidden="true" tabindex="-1"></a>mass <span class="ot"><-</span> mass <span class="sc">*</span> <span class="fl">2.0</span> <span class="co"># mass?</span></span>
<span id="cb8-4"><a href="#cb8-4" aria-hidden="true" tabindex="-1"></a>age <span class="ot"><-</span> age <span class="sc">-</span> <span class="dv">20</span> <span class="co"># age?</span></span>
<span id="cb8-5"><a href="#cb8-5" aria-hidden="true" tabindex="-1"></a>mass_index <span class="ot"><-</span> mass<span class="sc">/</span>age <span class="co"># mass_index?</span></span></code></pre></div>
<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>mass <span class="ot"><-</span> <span class="fl">47.5</span> <span class="co"># mass is 47.5</span></span>
<span id="cb9-2"><a href="#cb9-2" aria-hidden="true" tabindex="-1"></a>age <span class="ot"><-</span> <span class="dv">122</span> <span class="co"># age is 122</span></span>
<span id="cb9-3"><a href="#cb9-3" aria-hidden="true" tabindex="-1"></a>mass <span class="ot"><-</span> mass <span class="sc">*</span> <span class="fl">2.0</span> <span class="co"># mass is 95</span></span>
<span id="cb9-4"><a href="#cb9-4" aria-hidden="true" tabindex="-1"></a>age <span class="ot"><-</span> age <span class="sc">-</span> <span class="dv">20</span> <span class="co"># age is 102</span></span>
<span id="cb9-5"><a href="#cb9-5" aria-hidden="true" tabindex="-1"></a>mass_index <span class="ot"><-</span> mass<span class="sc">/</span>age <span class="co"># mass_index is 0.931</span></span></code></pre></div>
</div>
</div>
</blockquote>
<p><br/></p>
</div>
<div id="functions-and-their-arguments" class="section level3">
<h3>Functions and their arguments</h3>
<p>Functions are “canned scripts” that automate more complicated sets of
commands including operations assignments, etc. Many functions are
predefined, or can be made available by importing R <em>packages</em>
(more on that later). A function usually takes one or more inputs called
<em>arguments</em>. Functions often (but not always) return a
<em>value</em>. A typical example would be the function
<code>sqrt()</code>. The input (the argument) must be a number, and the
return value (in fact, the output) is the square root of that number.
Executing a function (‘running it’) is called <em>calling</em> the
function. An example of a function call is:</p>
<div class="sourceCode" id="cb10"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb10-1"><a href="#cb10-1" aria-hidden="true" tabindex="-1"></a>b <span class="ot"><-</span> <span class="fu">sqrt</span>(a)</span></code></pre></div>
<p>Here, the value of <code>a</code> is given to the <code>sqrt()</code>
function, the <code>sqrt()</code> function calculates the square root,
and returns the value which is then assigned to the object
<code>b</code>. This function is very simple, because it takes just one
argument.</p>
<p>The return ‘value’ of a function need not be numerical (like that of
<code>sqrt()</code>), and it also does not need to be a single item: it
can be a set of things, or even a dataset. We’ll see that when we read
data files into R.</p>
<p>Arguments can be anything, not only numbers or filenames, but also
other objects. Exactly what each argument means differs per function,
and must be looked up in the documentation (see below). Some functions
take arguments which may either be specified by the user, or, if left
out, take on a <em>default</em> value: these are called
<em>options</em>. Options are typically used to alter the way the
function operates, such as whether it ignores ‘bad values’, or what
symbol to use in a plot. However, if you want something specific, you
can specify a value of your choice which will be used instead of the
default.</p>
<p>Let’s try a function that can take multiple arguments:
<code>round()</code>.</p>
<div class="sourceCode" id="cb11"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb11-1"><a href="#cb11-1" aria-hidden="true" tabindex="-1"></a><span class="fu">round</span>(<span class="fl">3.14159</span>)</span></code></pre></div>
<pre><code>#> [1] 3</code></pre>
<p>Here, we’ve called <code>round()</code> with just one argument,
<code>3.14159</code>, and it has returned the value <code>3</code>.
That’s because the default is to round to the nearest whole number. If
we want more digits we can see how to do that by getting information
about the <code>round</code> function. We can use
<code>args(round)</code> to find what arguments it takes, or look at the
help for this function using <code>?round</code>.</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="fu">args</span>(round)</span></code></pre></div>
<pre><code>#> function (x, digits = 0)
#> NULL</code></pre>
<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>?round</span></code></pre></div>
<p>We see that if we want a different number of digits, we can type
<code>digits = 2</code> or however many we want.</p>
<div class="sourceCode" 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">round</span>(<span class="fl">3.14159</span>, <span class="at">digits =</span> <span class="dv">2</span>)</span></code></pre></div>
<pre><code>#> [1] 3.14</code></pre>
<p>If you provide the arguments in the exact same order as they are
defined you don’t have to name them:</p>
<div class="sourceCode" 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">round</span>(<span class="fl">3.14159</span>, <span class="dv">2</span>)</span></code></pre></div>
<pre><code>#> [1] 3.14</code></pre>
<p>And if you do name the arguments, you can switch their order:</p>
<div class="sourceCode" id="cb20"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb20-1"><a href="#cb20-1" aria-hidden="true" tabindex="-1"></a><span class="fu">round</span>(<span class="at">digits =</span> <span class="dv">2</span>, <span class="at">x =</span> <span class="fl">3.14159</span>)</span></code></pre></div>
<pre><code>#> [1] 3.14</code></pre>
<p>It’s good practice to put the non-optional arguments (like the number
you’re rounding) first in your function call, and to then specify the
names of all optional arguments. If you don’t, someone reading your code
might have to look up the definition of a function with unfamiliar
arguments to understand what you’re doing.</p>
</div>
</div>
<div id="vectors-and-data-types" class="section level2">
<h2>Vectors and data types</h2>
<p>A vector is the most common and basic data type in R, and is pretty
much the workhorse of R. A vector is composed by a series of values,
which can be either numbers or characters. We can assign a series of
values to a vector using the <code>c()</code> function. For example we
can create a vector of animal weights and assign it to a new object
<code>weight_g</code>:</p>
<div class="sourceCode" id="cb22"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb22-1"><a href="#cb22-1" aria-hidden="true" tabindex="-1"></a>weight_g <span class="ot"><-</span> <span class="fu">c</span>(<span class="dv">50</span>, <span class="dv">60</span>, <span class="dv">65</span>, <span class="dv">82</span>)</span>
<span id="cb22-2"><a href="#cb22-2" aria-hidden="true" tabindex="-1"></a>weight_g</span></code></pre></div>
<p>A vector can also contain characters:</p>
<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>animals <span class="ot"><-</span> <span class="fu">c</span>(<span class="st">"mouse"</span>, <span class="st">"rat"</span>, <span class="st">"dog"</span>)</span>
<span id="cb23-2"><a href="#cb23-2" aria-hidden="true" tabindex="-1"></a>animals</span></code></pre></div>
<p>The quotes around “mouse”, “rat”, etc. are essential here. Without
the quotes R will assume objects have been created called
<code>mouse</code>, <code>rat</code> and <code>dog</code>. As these
objects don’t exist in R’s memory, there will be an error message.</p>
<p>There are many functions that allow you to inspect the content of a
vector. <code>length()</code> tells you how many elements are in a
particular vector:</p>
<div class="sourceCode" 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">length</span>(weight_g)</span>
<span id="cb24-2"><a href="#cb24-2" aria-hidden="true" tabindex="-1"></a><span class="fu">length</span>(animals)</span></code></pre></div>
<p>An important feature of a vector, is that all of the elements are the
same type of data. The function <code>class()</code> indicates the class
(the type of element) of an object:</p>
<div class="sourceCode" id="cb25"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb25-1"><a href="#cb25-1" aria-hidden="true" tabindex="-1"></a><span class="fu">class</span>(weight_g)</span>
<span id="cb25-2"><a href="#cb25-2" aria-hidden="true" tabindex="-1"></a><span class="fu">class</span>(animals)</span></code></pre></div>
<p>The function <code>str()</code> provides an overview of the structure
of an object and its elements. It is a useful function when working with
large and complex objects:</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="fu">str</span>(weight_g)</span>
<span id="cb26-2"><a href="#cb26-2" aria-hidden="true" tabindex="-1"></a><span class="fu">str</span>(animals)</span></code></pre></div>
<p>You can use the <code>c()</code> function to add other elements to
your vector:</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>weight_g <span class="ot"><-</span> <span class="fu">c</span>(weight_g, <span class="dv">90</span>) <span class="co"># add to the end of the vector</span></span>
<span id="cb27-2"><a href="#cb27-2" aria-hidden="true" tabindex="-1"></a>weight_g <span class="ot"><-</span> <span class="fu">c</span>(<span class="dv">30</span>, weight_g) <span class="co"># add to the beginning of the vector</span></span>
<span id="cb27-3"><a href="#cb27-3" aria-hidden="true" tabindex="-1"></a>weight_g</span></code></pre></div>
<p>In the first line, we take the original vector <code>weight_g</code>,
add the value <code>90</code> to the end of it, and save the result back
into <code>weight_g</code>. Then we add the value <code>30</code> to the
beginning, again saving the result back into <code>weight_g</code>.</p>
<p>We can do this over and over again to grow a vector, or assemble a
dataset. As we program, this may be useful to add results that we are
collecting or calculating.</p>
<p>An <strong>atomic vector</strong> is the simplest R <strong>data
type</strong> and is a linear vector of a single type. Above, we saw 2
of the 6 main <strong>atomic vector</strong> types that R uses:
<code>"character"</code> and <code>"numeric"</code> (or
<code>"double"</code>). These are the basic building blocks that all R
objects are built from. The other 4 <strong>atomic vector</strong> types
are:</p>
<ul>
<li><code>"logical"</code> for <code>TRUE</code> and <code>FALSE</code>
(the boolean data type)</li>
<li><code>"integer"</code> for integer numbers (e.g., <code>2L</code>,
the <code>L</code> indicates to R that it’s an integer)</li>
<li><code>"complex"</code> to represent complex numbers with real and
imaginary parts (e.g., <code>1 + 4i</code>) and that’s all we’re going
to say about them</li>
<li><code>"raw"</code> for bitstreams that we won’t discuss further</li>
</ul>
<p>You can check the type of your vector using the <code>typeof()</code>
function and inputting your vector as the argument.</p>
<p>Vectors are one of the many <strong>data structures</strong> that R
uses. Other important ones are lists (<code>list</code>), matrices
(<code>matrix</code>), data frames (<code>data.frame</code>), factors
(<code>factor</code>) and arrays (<code>array</code>).</p>
<blockquote>
<h3 id="challenge-1">Challenge</h3>
<ol style="list-style-type: decimal">
<li>Create a vector <code>height_mm</code> that contains the following
heights of animals 100,150,99,87 in mm respectively.</li>
</ol>
<div class="accordion">
<h3 class="toc-ignore">
Answer
</h3>
<div style="background: #fff;">
<div class="sourceCode" id="cb28"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb28-1"><a href="#cb28-1" aria-hidden="true" tabindex="-1"></a>height_mm <span class="ot"><-</span> <span class="fu">c</span>(<span class="dv">100</span>, <span class="dv">150</span>, <span class="dv">99</span>, <span class="dv">87</span>)</span></code></pre></div>
</div>
</div>
<ol start="2" style="list-style-type: decimal">
<li>What is the total height of these animals in mm? (<em>Hint</em>: use
function <code>sum</code>)</li>
</ol>
<div class="accordion">
<h3 class="toc-ignore">
Answer
</h3>
<div style="background: #fff;">
<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">sum</span>(height_mm)</span></code></pre></div>
</div>
</div>
<ol start="3" style="list-style-type: decimal">
<li>Another animal was measured and its height is 220mm. Add this to the
beginning of the vector <code>height_mm</code> and save the total height
of the new set of animals in the <code>total_height</code> variable.
What is the new total_height?</li>
</ol>
<div class="accordion">
<h3 class="toc-ignore">
Answer
</h3>
<div style="background: #fff;">
<div class="sourceCode" id="cb30"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb30-1"><a href="#cb30-1" aria-hidden="true" tabindex="-1"></a>height_mm <span class="ot"><-</span> <span class="fu">c</span>(<span class="dv">220</span>, height_mm)</span>
<span id="cb30-2"><a href="#cb30-2" aria-hidden="true" tabindex="-1"></a>total_height <span class="ot"><-</span> <span class="fu">sum</span>(height_mm)</span></code></pre></div>
</div>
</div>
</blockquote>
</div>
<div id="subsetting-vectors" class="section level2">
<h2>Subsetting vectors</h2>
<p>If we want to extract one or several values from a vector, we must
provide one or several indices in square brackets. For instance:</p>
<div class="sourceCode" id="cb31"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb31-1"><a href="#cb31-1" aria-hidden="true" tabindex="-1"></a>animals <span class="ot"><-</span> <span class="fu">c</span>(<span class="st">"mouse"</span>, <span class="st">"rat"</span>, <span class="st">"dog"</span>, <span class="st">"cat"</span>)</span>
<span id="cb31-2"><a href="#cb31-2" aria-hidden="true" tabindex="-1"></a>animals[<span class="dv">2</span>]</span></code></pre></div>
<pre><code>#> [1] "rat"</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>animals[<span class="fu">c</span>(<span class="dv">3</span>, <span class="dv">2</span>)]</span></code></pre></div>
<pre><code>#> [1] "dog" "rat"</code></pre>
<p>We can also repeat the indices to create an object with more elements
than the original one:</p>
<div class="sourceCode" id="cb35"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb35-1"><a href="#cb35-1" aria-hidden="true" tabindex="-1"></a>more_animals <span class="ot"><-</span> animals[<span class="fu">c</span>(<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>, <span class="dv">2</span>, <span class="dv">1</span>, <span class="dv">4</span>)]</span>
<span id="cb35-2"><a href="#cb35-2" aria-hidden="true" tabindex="-1"></a>more_animals</span></code></pre></div>
<pre><code>#> [1] "mouse" "rat" "dog" "rat" "mouse" "cat"</code></pre>
<p>R indices start at 1. Programming languages like Fortran, MATLAB,
Julia, and R start counting at 1, because that’s what human beings
typically do. Languages in the C family (including C++, Java, Perl, and
Python) count from 0 because that’s simpler for computers to do.</p>
<div id="conditional-subsetting" class="section level3">
<h3>Conditional subsetting</h3>
<p>Another common way of subsetting is by using a logical vector.
<code>TRUE</code> will select the element with the same index, while
<code>FALSE</code> will not:</p>
<div class="sourceCode" id="cb37"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb37-1"><a href="#cb37-1" aria-hidden="true" tabindex="-1"></a>weight_g <span class="ot"><-</span> <span class="fu">c</span>(<span class="dv">21</span>, <span class="dv">34</span>, <span class="dv">39</span>, <span class="dv">54</span>, <span class="dv">55</span>)</span>
<span id="cb37-2"><a href="#cb37-2" aria-hidden="true" tabindex="-1"></a>weight_g[<span class="fu">c</span>(<span class="cn">TRUE</span>, <span class="cn">FALSE</span>, <span class="cn">TRUE</span>, <span class="cn">TRUE</span>, <span class="cn">FALSE</span>)]</span></code></pre></div>
<pre><code>#> [1] 21 39 54</code></pre>
<p>Typically, these logical vectors are not typed by hand, but are the
output of other functions or logical tests. For instance, if you wanted
to select only the values above 50:</p>
<div class="sourceCode" id="cb39"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb39-1"><a href="#cb39-1" aria-hidden="true" tabindex="-1"></a>weight_g <span class="sc">></span> <span class="dv">50</span> <span class="co"># will return logicals with TRUE for the indices that meet the condition</span></span></code></pre></div>
<pre><code>#> [1] FALSE FALSE FALSE TRUE TRUE</code></pre>
<div class="sourceCode" id="cb41"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb41-1"><a href="#cb41-1" aria-hidden="true" tabindex="-1"></a><span class="do">## so we can use this to select only the values above 50</span></span>
<span id="cb41-2"><a href="#cb41-2" aria-hidden="true" tabindex="-1"></a>weight_g[weight_g <span class="sc">></span> <span class="dv">50</span>]</span></code></pre></div>
<pre><code>#> [1] 54 55</code></pre>
<p>You can combine multiple tests using <code>&</code> (both
conditions are true, AND) or <code>|</code> (at least one of the
conditions is true, OR):</p>
<div class="sourceCode" id="cb43"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb43-1"><a href="#cb43-1" aria-hidden="true" tabindex="-1"></a>weight_g[weight_g <span class="sc"><</span> <span class="dv">30</span> <span class="sc">|</span> weight_g <span class="sc">></span> <span class="dv">50</span>]</span></code></pre></div>
<pre><code>#> [1] 21 54 55</code></pre>
<div class="sourceCode" id="cb45"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb45-1"><a href="#cb45-1" aria-hidden="true" tabindex="-1"></a>weight_g[weight_g <span class="sc">>=</span> <span class="dv">30</span> <span class="sc">&</span> weight_g <span class="sc">==</span> <span class="dv">21</span>]</span></code></pre></div>
<pre><code>#> numeric(0)</code></pre>
<p>Here, <code><</code> stands for “less than”, <code>></code> for
“greater than”, <code>>=</code> for “greater than or equal to”, and
<code>==</code> for “equal to”. The double equal sign <code>==</code> is
a test for numerical equality between the left and right hand sides, and
should not be confused with the single <code>=</code> sign, which
performs variable assignment (similar to <code><-</code>).</p>
<p>A common task is to search for certain strings in a vector. One could
use the “or” operator <code>|</code> to test for equality to multiple
values, but this can quickly become tedious. The function
<code>%in%</code> allows you to test if any of the elements of a search
vector are found:</p>
<div class="sourceCode" id="cb47"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb47-1"><a href="#cb47-1" aria-hidden="true" tabindex="-1"></a>animals <span class="ot"><-</span> <span class="fu">c</span>(<span class="st">"mouse"</span>, <span class="st">"rat"</span>, <span class="st">"dog"</span>, <span class="st">"cat"</span>)</span>
<span id="cb47-2"><a href="#cb47-2" aria-hidden="true" tabindex="-1"></a>animals[animals <span class="sc">==</span> <span class="st">"cat"</span> <span class="sc">|</span> animals <span class="sc">==</span> <span class="st">"rat"</span>] <span class="co"># returns both rat and cat</span></span></code></pre></div>
<pre><code>#> [1] "rat" "cat"</code></pre>
<div class="sourceCode" id="cb49"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb49-1"><a href="#cb49-1" aria-hidden="true" tabindex="-1"></a>animals <span class="sc">%in%</span> <span class="fu">c</span>(<span class="st">"rat"</span>, <span class="st">"cat"</span>, <span class="st">"dog"</span>, <span class="st">"duck"</span>, <span class="st">"goat"</span>)</span></code></pre></div>
<pre><code>#> [1] FALSE TRUE TRUE TRUE</code></pre>
<div class="sourceCode" id="cb51"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb51-1"><a href="#cb51-1" aria-hidden="true" tabindex="-1"></a>animals[animals <span class="sc">%in%</span> <span class="fu">c</span>(<span class="st">"rat"</span>, <span class="st">"cat"</span>, <span class="st">"dog"</span>, <span class="st">"duck"</span>, <span class="st">"goat"</span>)]</span></code></pre></div>
<pre><code>#> [1] "rat" "dog" "cat"</code></pre>
</div>
</div>
<div id="missing-data" class="section level2">
<h2>Missing data</h2>
<p>As R was designed to analyze datasets, it includes the concept of
missing data (which is uncommon in other programming languages). Missing
data are represented in vectors as <code>NA</code>.</p>
<p>When doing operations on numbers, most functions will return
<code>NA</code> if the data you are working with include missing values.
This feature makes it harder to overlook the cases where you are dealing
with missing data. You can add the argument <code>na.rm = TRUE</code> to
calculate the result while ignoring the missing values.</p>
<div class="sourceCode" id="cb53"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb53-1"><a href="#cb53-1" aria-hidden="true" tabindex="-1"></a>heights <span class="ot"><-</span> <span class="fu">c</span>(<span class="dv">2</span>, <span class="dv">4</span>, <span class="dv">4</span>, <span class="cn">NA</span>, <span class="dv">6</span>)</span>
<span id="cb53-2"><a href="#cb53-2" aria-hidden="true" tabindex="-1"></a><span class="fu">mean</span>(heights)</span>
<span id="cb53-3"><a href="#cb53-3" aria-hidden="true" tabindex="-1"></a><span class="fu">max</span>(heights)</span>
<span id="cb53-4"><a href="#cb53-4" aria-hidden="true" tabindex="-1"></a><span class="fu">mean</span>(heights, <span class="at">na.rm =</span> <span class="cn">TRUE</span>)</span>
<span id="cb53-5"><a href="#cb53-5" aria-hidden="true" tabindex="-1"></a><span class="fu">max</span>(heights, <span class="at">na.rm =</span> <span class="cn">TRUE</span>)</span></code></pre></div>
<p>If your data include missing values, you may want to become familiar
with the functions <code>is.na()</code>, <code>na.omit()</code>, and
<code>complete.cases()</code>. See below for examples.</p>
<div class="sourceCode" id="cb54"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb54-1"><a href="#cb54-1" aria-hidden="true" tabindex="-1"></a><span class="do">## Extract those elements which are not missing values.</span></span>
<span id="cb54-2"><a href="#cb54-2" aria-hidden="true" tabindex="-1"></a>heights[<span class="sc">!</span><span class="fu">is.na</span>(heights)]</span>
<span id="cb54-3"><a href="#cb54-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb54-4"><a href="#cb54-4" aria-hidden="true" tabindex="-1"></a><span class="do">## Returns the object with incomplete cases removed. The returned object is an atomic vector of type `"numeric"` (or `"double"`).</span></span>
<span id="cb54-5"><a href="#cb54-5" aria-hidden="true" tabindex="-1"></a><span class="fu">na.omit</span>(heights)</span>
<span id="cb54-6"><a href="#cb54-6" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb54-7"><a href="#cb54-7" aria-hidden="true" tabindex="-1"></a><span class="do">## Extract those elements which are complete cases. The returned object is an atomic vector of type `"numeric"` (or `"double"`).</span></span>
<span id="cb54-8"><a href="#cb54-8" aria-hidden="true" tabindex="-1"></a>heights[<span class="fu">complete.cases</span>(heights)]</span></code></pre></div>
<p>Recall that you can use the <code>typeof()</code> function to find
the type of your atomic vector.</p>
<blockquote>
<h3 id="challenge-2">Challenge</h3>
<ol style="list-style-type: decimal">
<li><p>Using this vector of heights in inches, create a new vector,
<code>heights_no_na</code>, with the NAs removed.</p>
<div class="sourceCode" id="cb55"><pre
class="sourceCode r"><code class="sourceCode r"><span id="cb55-1"><a href="#cb55-1" aria-hidden="true" tabindex="-1"></a>heights <span class="ot"><-</span> <span class="fu">c</span>(<span class="dv">63</span>, <span class="dv">69</span>, <span class="dv">60</span>, <span class="dv">65</span>, <span class="cn">NA</span>, <span class="dv">68</span>, <span class="dv">61</span>, <span class="dv">70</span>, <span class="dv">61</span>, <span class="dv">59</span>, <span class="dv">64</span>, <span class="dv">69</span>, <span class="dv">63</span>, <span class="dv">63</span>, <span class="cn">NA</span>, <span class="dv">72</span>, <span class="dv">65</span>, <span class="dv">64</span>, <span class="dv">70</span>, <span class="dv">63</span>, <span class="dv">65</span>)</span></code></pre></div></li>
<li><p>Use the function <code>median()</code> to calculate the median of
the <code>heights</code> vector.</p></li>
<li><p>How many people in the set are taller than 67 inches.</p></li>
</ol>
<div class="accordion">
<h3 class="toc-ignore">
Answer
</h3>
<div style="background: #fff;">
<div class="sourceCode" id="cb56"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb56-1"><a href="#cb56-1" aria-hidden="true" tabindex="-1"></a>heights <span class="ot"><-</span> <span class="fu">c</span>(<span class="dv">63</span>, <span class="dv">69</span>, <span class="dv">60</span>, <span class="dv">65</span>, <span class="cn">NA</span>, <span class="dv">68</span>, <span class="dv">61</span>, <span class="dv">70</span>, <span class="dv">61</span>, <span class="dv">59</span>, <span class="dv">64</span>, <span class="dv">69</span>, <span class="dv">63</span>, <span class="dv">63</span>, <span class="cn">NA</span>, <span class="dv">72</span>, <span class="dv">65</span>, <span class="dv">64</span>, <span class="dv">70</span>, <span class="dv">63</span>, <span class="dv">65</span>)</span>
<span id="cb56-2"><a href="#cb56-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb56-3"><a href="#cb56-3" aria-hidden="true" tabindex="-1"></a><span class="co"># 1.</span></span>
<span id="cb56-4"><a href="#cb56-4" aria-hidden="true" tabindex="-1"></a>heights_no_na <span class="ot"><-</span> heights[<span class="sc">!</span><span class="fu">is.na</span>(heights)] </span>
<span id="cb56-5"><a href="#cb56-5" aria-hidden="true" tabindex="-1"></a><span class="co"># or</span></span>
<span id="cb56-6"><a href="#cb56-6" aria-hidden="true" tabindex="-1"></a>heights_no_na <span class="ot"><-</span> <span class="fu">na.omit</span>(heights)</span>
<span id="cb56-7"><a href="#cb56-7" aria-hidden="true" tabindex="-1"></a><span class="co"># or</span></span>
<span id="cb56-8"><a href="#cb56-8" aria-hidden="true" tabindex="-1"></a>heights_no_na <span class="ot"><-</span> heights[<span class="fu">complete.cases</span>(heights)]</span>
<span id="cb56-9"><a href="#cb56-9" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb56-10"><a href="#cb56-10" aria-hidden="true" tabindex="-1"></a><span class="co"># 2.</span></span>
<span id="cb56-11"><a href="#cb56-11" aria-hidden="true" tabindex="-1"></a><span class="fu">median</span>(heights, <span class="at">na.rm =</span> <span class="cn">TRUE</span>)</span>
<span id="cb56-12"><a href="#cb56-12" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb56-13"><a href="#cb56-13" aria-hidden="true" tabindex="-1"></a><span class="co"># 3.</span></span>
<span id="cb56-14"><a href="#cb56-14" aria-hidden="true" tabindex="-1"></a>heights_above_67 <span class="ot"><-</span> heights_no_na[heights_no_na <span class="sc">></span> <span class="dv">67</span>]</span>
<span id="cb56-15"><a href="#cb56-15" aria-hidden="true" tabindex="-1"></a><span class="fu">length</span>(heights_above_67)</span></code></pre></div>
</div>
</div>
</blockquote>
</div>
</div>
</div>
</div>
<script>
// add bootstrap table styles to pandoc tables
function bootstrapStylePandocTables() {
$('tr.odd').parent('tbody').parent('table').addClass('table table-condensed');
}
$(document).ready(function () {
bootstrapStylePandocTables();
});
</script>
<!-- tabsets -->
<script>
$(document).ready(function () {
window.buildTabsets("TOC");
});
$(document).ready(function () {
$('.tabset-dropdown > .nav-tabs > li').click(function () {
$(this).parent().toggleClass('nav-tabs-open');
});
});
</script>
<!-- code folding -->
<script>
$(document).ready(function () {
// temporarily add toc-ignore selector to headers for the consistency with Pandoc
$('.unlisted.unnumbered').addClass('toc-ignore')
// 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,h4",
theme: "bootstrap3",
context: '.toc-content',
hashGenerator: function (text) {
return text.replace(/[.\\/?&!#<>]/g, '').replace(/\s/g, '_');
},
ignoreSelector: ".toc-ignore",
scrollTo: 0
};
options.showAndHide = false;
options.smoothScroll = true;
// tocify
var toc = $("#TOC").tocify(options).data("toc-tocify");
});
</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>