-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathRBasics.html
More file actions
895 lines (745 loc) · 35.7 KB
/
RBasics.html
File metadata and controls
895 lines (745 loc) · 35.7 KB
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
<!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="Clarke Iakovakis" />
<title>R Basics</title>
<script src="site_libs/header-attrs-2.9/header-attrs.js"></script>
<script src="site_libs/jquery-1.11.3/jquery.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="site_libs/bootstrap-3.3.5/css/spacelab.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.11.4/jquery-ui.min.js"></script>
<link href="site_libs/tocify-1.9.1/jquery.tocify.css" rel="stylesheet" />
<script src="site_libs/tocify-1.9.1/jquery.tocify.js"></script>
<script src="site_libs/navigation-1.1/tabsets.js"></script>
<link href="site_libs/highlightjs-9.12.0/default.css" rel="stylesheet" />
<script src="site_libs/highlightjs-9.12.0/highlight.js"></script>
<link href="site_libs/pagedtable-1.1/css/pagedtable.css" rel="stylesheet" />
<script src="site_libs/pagedtable-1.1/js/pagedtable.js"></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;}</style>
<script type="text/javascript">
if (window.hljs) {
hljs.configure({languages: []});
hljs.initHighlightingOnLoad();
if (document.readyState && document.readyState === "complete") {
window.setTimeout(function() { hljs.initHighlighting(); }, 0);
}
}
</script>
<link rel="stylesheet" href="styles.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;
}
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 it active
menuAnchor.tab('show');
// if it's got a parent navbar menu mark it active as well
menuAnchor.closest('li.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 {
content: "";
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: "";
border: none;
}
.tabset-dropdown > .nav-tabs.nav-tabs-open:before {
content: "";
font-family: 'Glyphicons Halflings';
display: inline-block;
padding: 10px;
border-right: 1px solid #ddd;
}
.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">Clarke Iakovakis</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
FSCI 2021 W25 Session
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="fsci_syllabus.html">Course syllabus</a>
</li>
<li>
<a href="using_jupyter_notebooks.html">Jupyter Notebooks and Binder</a>
</li>
<li>
<a href="IntroductionToR.html">Introduction to R</a>
</li>
<li>
<a href="RBasics.html">R Basics</a>
</li>
<li>
<a href="DataExploration.html">Data Exploration</a>
</li>
<li>
<a href="jennybc_lists_lesson.html">Exploring Data in Lists</a>
</li>
<li>
<a href="rcrossref.html">rcrossref</a>
</li>
<li>
<a href="rorcid.html">rorcid</a>
</li>
</ul>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
</ul>
</div><!--/.nav-collapse -->
</div><!--/.container -->
</div><!--/.navbar -->
<div id="header">
<h1 class="title toc-ignore">R Basics</h1>
<h4 class="author">Clarke Iakovakis</h4>
</div>
<div id="binder-link-to-this-notebook" class="section level1">
<h1>Binder link to this notebook:</h1>
<p><a href="https://mybinder.org/v2/gh/ciakovx/ciakovx.github.io/master?filepath=RBasics.ipynb"><img src="https://mybinder.org/badge_logo.svg" alt="Binder" /></a></p>
<p><a href="https://mybinder.org/v2/gh/ciakovx/ciakovx.github.io/master?filepath=RBasics.ipynb" class="uri">https://mybinder.org/v2/gh/ciakovx/ciakovx.github.io/master?filepath=RBasics.ipynb</a></p>
<p>Please note the Binder link is condensed and modified for the Jupyter Notebooks environment, whereas this page is longer and pertains to the R Studio environment.</p>
</div>
<div id="introduction" class="section level1">
<h1>Introduction</h1>
<p>This guide accompanies the first day of instruction for our course at the 2021 FORCE11 Scholarly Communications Institute: <a href="https://www.force11.org/fsci/2021/course-list-abstracts#W25">“W25 - Working with Scholarly Literature in R: Pulling, Wrangling, Cleaning, and Analyzing Structured Bibliographic Metadata.”</a>. It covers basic nuts and bolts of using R.</p>
<p>This walkthrough is distributed under a <a href="https://creativecommons.org/licenses/by/4.0/">Creative Commons Attribution 4.0 International (CC BY 4.0) License</a>.</p>
<p><img src="RBasics_files/figure-html/unnamed-chunk-1-1.png" width="672" /></p>
</div>
<div id="writing-evaluating-expressions" class="section level1">
<h1>Writing & Evaluating Expressions</h1>
<p>The <em>prompt</em> is the blinking cursor in the console pane prompting you to take action, in the lower-left corner of R Studio. We type <em>expressions</em> into the prompt, and press the Enter key to <em>evaluate</em> those expressions.</p>
<p>You can also use R like a calculator, as you saw in the previous set of exercises.</p>
<pre class="r"><code>2 + 2
## [1] 4</code></pre>
<p>You can perform all kinds of mathematical operations using R, but we will not be covering that in our session today.</p>
<div id="assigning-values" class="section level2">
<h2>Assigning values</h2>
<p>The first operator you’re going to come across is the assignment operator. This is the angle bracket (AKA the “less than”" symbol): <code><</code>, which you’ll get by pressing <strong>Shift + comma</strong> and the hyphen <code>-</code> which is located next to the zero key. There is no space between them, and it is designed to look like a left pointing arrow <code><-</code>.</p>
<pre class="r"><code># assign 5 to y by typing this in the console and pressing Enter
y <- 5</code></pre>
<p>Here I am creating a symbol called <code>y</code> and I’m <em>assigning</em> it the numeric value 5. Some R users would say “y <em>gets</em> 5.” Lowercase <code>y</code>, is now a <em>numeric vector</em> with one element. Or you could say <code>y</code> is a numeric vector, and the first element is the number 5. When you assign something to a symbol, nothing happens in the console, but in the Environment pane in the upper right, you will notice a new object, y.</p>
<p><img src="RBasics_files/figure-html/unnamed-chunk-2-1.png" width="672" /></p>
</div>
<div id="evaluating-expressions" class="section level2">
<h2>Evaluating Expressions</h2>
<p>If you now type <code>y</code> into the console, and press Enter on your keyboard, R will <em>evaluate</em> the expression. In this case, R will <em>print</em> the elements that are assigned to <code>y</code> (the number 5). We can do this easily since y only has one element, but if you do this with a large dataset loaded into R, it will obliterate your console because it will print the entire thing. The <code>[1]</code> indicates that the number 5 is the first element of this vector.</p>
<pre class="r"><code># evaluate y
y
## [1] 5
# you can also use the print() function
print(y)
## [1] 5</code></pre>
<p>Note that you can type <em>comments</em> into your code by using the hash symbol <code>#</code>. Anything following the hash symbol will not be evaluated. Comments are essential to helping you remember what your code does, and explaining it to others. Commenting code, along with documenting how data is collected and explaining what each variable represents, is essential to <a href="https://ropensci.github.io/reproducibility-guide/sections/introduction/">reproducibile research</a>.</p>
<pre class="r"><code># add 20 to y
y + 20
## [1] 25</code></pre>
<p>You can assign anything to any variable, and then perform operations on or with that variable. Try typing in the expression <code>y + 20</code> and press enter. R prints the number 25 to the console.</p>
<hr />
<p><strong>TRY IT YOURSELF</strong></p>
<ol style="list-style-type: decimal">
<li>Make sure that 5 is assigned to <code>y</code> by typing in <code>y <- 5</code></li>
<li>Assign the number 10 to variable <code>x</code>. Add <code>x</code> and <code>y</code> and evaluate the expression.</li>
<li>Assign <code>x + y</code> to variable <code>myTotal</code>. Look in the Environment pane to see what <code>myTotal</code> contains.</li>
<li>Run <code>View(myTotal)</code> to see it in the Data Viewer</li>
</ol>
<hr />
</div>
<div id="tips-for-assigning-values" class="section level2">
<h2>Tips for assigning values</h2>
<ul>
<li><strong>Do not use names of functions that already exist in R:</strong> The assignment operator assigns a value to a symbol. We can pretty much pick any symbol, or name, for that variable, as long as it is not already a function in R. For example, you wouldn’t want to name a variable <code>sum</code> because if you might end up in a confusing situation writing <code>sum(sum)</code></li>
<li><strong>R is case sensitive</strong>: It is important to note that R is <em>case sensitive.</em> If you try evaluating a capital <code>Y</code>, you will be told <code>Error in eval(expr, envir, enclos): object 'Y' not found</code>.</li>
<li><strong>No blank spaces or symbols other than underscores</strong>: R users get around this in a couple of ways, either through capitalization (e.g. <code>myData</code>) or underscores (e.g. <code>my_data</code>).</li>
<li><strong>Do not begin with numbers or symbols</strong>: Try to evaluate <code>1z <- 4</code> or <code>%z <- 4</code> and read the error message.</li>
<li><strong>Be descriptive, but make your variable names short</strong>: It’s good practice to be descriptive with your variable names. If you’re loading in a lot of data, choosing <code>myData</code> or <code>x</code> as a name may not be as helpful as, say, <code>ebookUsage</code>. Finally, keep your variable names short, since you will likely be typing them in frequently.</li>
</ul>
</div>
</div>
<div id="calling-a-function" class="section level1">
<h1>Calling a function</h1>
<p>R is a “functional programming language,” meaning it contains a number of <em>functions</em> you use to do something with your data. <em>Call</em> a function on a variable by entering the function into the console, followed by parentheses and the variables. For example, if you want to take the sum of 3 and 4, you can type in <code>sum(3, 4)</code>.</p>
<div id="function-arguments" class="section level2">
<h2>Function arguments</h2>
<p>Typing a question mark before a function will pull the help page up in the Navigation Pane in the lower right. Type <code>?sum</code> to view the help page for the <code>sum</code> function. You can also call <code>help(sum)</code>. This will provide the description of the function, how it is to be used, and the arguments.</p>
<p>In the case of <code>sum()</code>, the ellipses <code>. . .</code> represent an unlimited number of numeric elements. <code>sum()</code> also takes the argument <code>na.rm</code>. This is a logical (<code>TRUE/FALSE</code>) argument specifying if NA values (missing data) should be removed when the argument is evaluated.</p>
<p>The function <code>is.function()</code> will check if an argument is a function in R. If it is a function, it will print <code>TRUE</code> to the console.</p>
<pre class="r"><code># confirm that sum is a function
is.function(sum)
## [1] TRUE
# sum takes an unlimited number (. . .) of numeric elements
sum(3, 4, 5, 6, 7)
## [1] 25
# evaluating a sum with missing values will return NA
sum(3, 4, NA)
## [1] NA
# but setting the argument na.rm to TRUE will remove the NA
sum(3, 4, na.rm = TRUE)
## [1] 7</code></pre>
<p>Functions can be nested within each other. For example, <code>sqrt()</code> takes the square root of the number provided in the function call. Therefore you can run <code>sum(sqrt(9), 4)</code> to take the sum of the square root of 9 (3) and add it to 4. Or you could write the quadratic formula: <code>[(-b) + sqrt((b^2) - 4ac)] / (2*a)</code>.</p>
</div>
<div id="the-view-function" class="section level2">
<h2>The <code>View()</code> function</h2>
<p>Use this to open a tab in the Script Pane (upper left) to view your data. I use this all the time. You can also click on the variable name in the Environment Pane (upper right) to do the same thing.</p>
<pre class="r"><code>myDogs <- data.frame("breed" = c("beagle", "pug", "chihuahua")
, "shedding" = c("moderate", "high", "low"))
View(myDogs)</code></pre>
</div>
<div id="the-str-function" class="section level2">
<h2>The <code>str()</code> function</h2>
<p>Type <code>?str</code> into the console to read the description of the <code>str</code> function. You can call <code>str()</code> on an R object to compactly display information about it, including the data type, the number of elements, and a printout of the first few elements. We are going to use <code>str</code> in the following sections to investigate R objects, vectors, and data types.</p>
<pre class="r"><code># using str on a function will tell you what arguments it takes
str(sum)
# using str on an R object will give you information about that object</code></pre>
</div>
<div id="the-c-function" class="section level2">
<h2>The <code>c()</code> function</h2>
<p>Another important function is <code>c()</code> which will combine arguments to form a vector (more on vectors below). In some programs, such as Excel, this is called <em>concatenation</em>. If you read the help files for <code>c()</code> by calling <code>help(c)</code>, you can see that it takes an unlimited <code>. . .</code> number of arguments.</p>
<pre class="r"><code># use c() to combine three numbers into a vector, myFives
myFives <- c(5, 10, 15)
# call str() to see that myFives is a numeric vector of length 3
str(myFives)
## num [1:3] 5 10 15
# adding 5 will operate on each element of the vector. More on vectors below.
myFives + 5
## [1] 10 15 20</code></pre>
</div>
</div>
<div id="vectors" class="section level1">
<h1>Vectors</h1>
<p>Everything you manipulate in R is called an <em>object</em>. An object has a <em>class,</em> explained below. <em>Vectors</em> are the most basic type of object.</p>
<pre class="r"><code># create a vector of consecutive numbers 1-5
my_vector <- c(1, 2, 3, 4, 5)
# call `str()` to see myVector is a numeric vector of length 5
str(my_vector)
## num [1:5] 1 2 3 4 5
# Create a random sample of 5000 numbers between 1 and 2 million
my_long_vector <- sample(1:2000000, 5000)
# Evaluating this in the console will fill up your screen
print(my_long_vector)
# However, running View() on this vector fills the header with garbage
View(my_long_vector)
# Run it like this, where you coerce it to a data frame only for viewing purposes.
View(as.data.frame(my_long_vector))
# You can remove an object by calling rm()
rm(my_long_vector)
# Remove multiple items like this:
rm(list =c("my_long_vector", "my_vector"))
# Remove everything
rm(list = ls())</code></pre>
<div id="data-types-type" class="section level2">
<h2>Data types (type)</h2>
<p>A vector is a sequence of elements of the same <em>type</em>. Vectors can only contain “homogenous” data–in other words, all data must be of the same type. The type of a vector determines what kind of analysis you can do on it. For example, you can perform mathematical operations on <code>numeric</code> objects, but not on <code>character</code> objects. Below I will briefly review some of the data types in R and their type. You can call the <code>class()</code> function on an R object to find out it’s type. For example, running <code>class(sum)</code> will tell you that <code>sum()</code> is a function.</p>
<ul>
<li>Numeric or integer</li>
</ul>
<pre class="r"><code># create a vector of consecutive numbers 1-10 using the colon
my_integers <- c(1:10)
class(my_integers)
## [1] "integer"</code></pre>
<ul>
<li>Character</li>
</ul>
<pre class="r"><code># create a vector of book titles. Even though 1984 is composed of numbers, putting it in quotation marks makes it a character string
my_characters <- c("Macbeth", "Dracula", "1984")
class(my_characters)
## [1] "character"
# how many elements in this vector?
length(my_characters)
## [1] 3</code></pre>
<ul>
<li>Logical (binary <code>TRUE/FALSE</code>)</li>
</ul>
<pre class="r"><code># create a logical vector
my_logical <- c(TRUE, FALSE, FALSE, TRUE)
# you can also use the is.logical (or is.character, is.numeric) to verify an object's class
is.logical(my_logical)
## [1] TRUE
# you can also create logical vectors to use as an index
x <- c(2, 4, 8, 5, 1)
# create an index of TRUE/FALSE values where x is greater than 2
my_index <- x > 2
print(my_index)
## [1] FALSE TRUE TRUE TRUE FALSE
# subset x using that `my_index` in brackets (more on this later)
x[my_index]
## [1] 4 8 5</code></pre>
<ul>
<li>Factors
<ul>
<li>unordered (nominal)</li>
</ul></li>
</ul>
<pre class="r"><code># create a vector of type factor of item formats
my_nominal_factor <- factor(c("book","dissertation", "journal", "book", "dissertation"))
# print a table of the number of items in each format
table(my_nominal_factor)
## my_nominal_factor
## book dissertation journal
## 2 2 1 </code></pre>
<pre><code>+ ordered (ordinal)</code></pre>
<pre class="r"><code># create a vector of type factor of sizes
my_ordinal_factor <- c("small", "medium", "large", "small", "large")
# use the `ordered` function to specify the levels from small to medium to large. Notice that `levels` is an argument of `ordered`
my_ordinal_factor <- ordered(my_ordinal_factor
, levels = c("small", "medium", "large"))
# R now recognizes that small is smaller than medium, which is smaller than large
my_ordinal_factor
## [1] small medium large small large
## Levels: small < medium < large</code></pre>
<p>If you mix different objects in one vector, R will coerce the vector to be a single class. You can also coerce a vector to be a specific data type. This comes in handy when dealing with ISBNs, which are numeric, but we treat them as characters because we would never perform mathematical operations on them. Coerce data frames by using <code>as.character</code> or <code>as.numeric</code>, for example.</p>
<pre class="r"><code># create a vector of consecutive numbers 1-5
my_mixed_vector <- c(1:10, "a")
my_mixed_vector
## [1] "character"
# coerce the vector to an integer. R replaces the "a" with NA because `a` is not an integer
my_coerced_vector <- as.integer(my_mixed_vector)
## Warning message:
## NAs introduced by coercion
print(my_coerced_vector)
## [1] 1 2 3 4 5 6 7 8 9 10 NA</code></pre>
</div>
<div id="missing-values" class="section level2">
<h2>Missing values</h2>
<p>If our data is missing values, we can use <code>NA</code> to represent those. R functions have special actions when they encounter NA. How you deal with missing data in your analysis is a decision you will have to make–do you remove it entirely? Do you replace it with zeros? That will depend on your own methodological questions.</p>
<p>You can use <code>is.na()</code> to test if a value is NA or not. Conversely, use <code>complete.cases()</code> to test if a value is not missing.</p>
<pre class="r"><code># this expression has some nesting. I am creating a vector combining a sample of 5 letters `` and a repetition of NA five times `rep(NA, 5)`
my_nas <- c(letters[1:5], rep(NA, 5))
print(my_nas)
## [1] "a" "b" "c" "d" "e" NA NA NA NA NA
# Which values are NA?
is.na(my_nas)
## [1] FALSE FALSE FALSE FALSE FALSE TRUE TRUE TRUE TRUE TRUE
# Which values are complete?
complete.cases(my_nas)
## [1] TRUE TRUE TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE
# How many of each?
table(is.na(my_nas))
## FALSE TRUE
## 5 5
# use the brackets to subset the data and include complete cases only (more on this later)
my_completes <- my_nas[complete.cases(my_nas)]
print(my_completes)
## [1] "h" "k" "y" "w" "q"</code></pre>
<p>Helpful functions to provide information about vectors:</p>
<ul>
<li><code>length()</code> : number of elements in the vector</li>
<li><code>)</code> : returns the data type</li>
<li><code>str()</code> : compactly displays infomration about the vector</li>
<li><code>is.logical()</code>, <code>is.numeric()</code>, <code>is.character()</code>, etc. : verifies the data type (TRUE or FALSE)</li>
<li><code>as.logical()</code>, <code>as.numeric()</code>, <code>as.character()</code>, etc. : coerces the vector from one data type to another</li>
<li><code>is.na()</code> or <code>complete.cases()</code> : returns logical (TRUE/FALSE) vector of values that are NA or, conversely, that are complete</li>
</ul>
<hr />
<p><strong>TRY IT YOURSELF</strong></p>
<ol style="list-style-type: decimal">
<li>Assign the sum of 20 and 40 to variable <code>mySum</code></li>
<li>Use <code>is.function()</code> to check if <code>average</code> is a function. Use it to see if <code>mean</code> is a function.</li>
<li>Combine 5, 10, 15, NA into a vector <code>my_vec</code></li>
<li>Write an expression to get the average of the numbers in <code>my_vec</code>. Remove the NA if necessary.</li>
<li>Evaluate the following expressions and look at the return values.</li>
</ol>
<pre class="r"><code>my_numeric <- c(1, 2, 3, 4, 5)
my_characters <- c("Macbeth", "Dracula", "1984", "Jane Eyre", "Beowulf")
my_logical <- c(TRUE, FALSE, FALSE, TRUE, FALSE)
nchar(my_characters)
table(nchar(my_characters))
nchar("my_characters")
my_numeric + 2
as.numeric(my_logical)
my_numeric + my_logical
my_numeric > 3
my_numeric[my_numeric > 3]
c(my_numeric, NA)
is.na(c(my_numeric, NA))
c(my_numeric, "NA")
is.na(c(my_numeric, "NA"))
my_numeric[my_logical]
my_characters[my_logical]
my_numeric["my_logical"]</code></pre>
<hr />
</div>
<div id="subsetting-vectors" class="section level2">
<h2>Subsetting vectors</h2>
<p>You can use the brackets to subset a vector. Brackets can take either numeric values (which will correspond to the element in the order it exists in the vector) or logical (T/F) values. You can also use functions such as <code>which()</code>, that return numeric values.</p>
<pre class="r"><code># state.name is a built in vector in R of all U.S. states
state.name
state.name[1]
## [1] "Alabama"
state.name[1:5]
## [1] "Alabama" "Alaska" "Arizona" "Arkansas" "California"
# You must use the `c()` function if you have more than one value
state.name[1, 10, 20]
## Error in state.name[1, 10, 20] : incorrect number of dimensions
state.name[c(1, 10, 20)]
## [1] "Alabama" "Georgia" "Maryland"
# There's only one state called Alabama
table(state.name == "Alabama")
## FALSE TRUE
## 49 1
# create a logical vector of state names where "Alabama" == TRUE. Notice you have to use two equals signs.
myAlabamaIndex <- state.name == "Alabama"
myAlabamaIndex
## TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
# subset state.name using that T/F index (will return the only value where myAlabamaIndex == TRUE)
state.name[myAlabamaIndex]
## [1] "Alabama"
# create a logical vector of state names with more than 10 character names
ten_characters <- nchar(state.name) > 10
# you can find out which elements are TRUE values by using the `which()` function
which(ten_characters)
# subset state.names using `which()`
ten_character_state.names <- state.name[ten_characters]
ten_character_state.names
## [1] "Connecticut" "Massachusetts" "Mississippi" "New Hampshire" "North Carolina" "North Dakota" "Pennsylvania"
## [8] "Rhode Island" "South Carolina" "South Dakota" "West Virginia" </code></pre>
<hr />
<p><strong>TRY IT YOURSELF</strong></p>
<ol style="list-style-type: decimal">
<li>Subset <code>state.name</code> to include only element number 25. What state is element 25?</li>
<li>Subset <code>state.name</code> to include elements 3, 12, and 40. You will need to use the <code>c()</code> function.</li>
<li>Alabama is element number 1. What element number is New York?</li>
<li>Use the <code>table()</code> and the <code>nchar()</code> functions to find out how many state names have more than 7 characters.</li>
<li>Create a vector of only these states.</li>
</ol>
<hr />
<div style="page-break-after: always;"></div>
</div>
</div>
<div id="data-frames" class="section level1">
<h1>Data frames</h1>
<p>A data frame is the term in R for a spreadsheet style of data: a grid of rows and columns. The number of columns and rows is virtually unlimited, but each column must be a vector of the same length. A dataframe can comprise heterogeneous data: in other words, each column can be a different data type. However, because a column is a vector, it has to be a single data type.</p>
<div id="create-a-data-frame" class="section level2">
<h2>Create a data frame</h2>
<p>You will likely be importing your dataset, but it is easy to create a data frames on your own:</p>
<pre class="r"><code># create three vectors
title <- c("Macbeth","Dracula","1984")
author <- c("Shakespeare","Stoker","Orwell")
checkouts <- c(25, 15, 18)
available <- c(TRUE, FALSE, FALSE)
# create a data frame using the data.frame() function. Specify stringsAsFactors as FALSE
ebooks <- data.frame(title, author, checkouts, stringsAsFactors = F)</code></pre>
<p>You can print small data frames like this to the console using <code>print(ebooks)</code></p>
<pre><code> title author checkouts
1 Macbeth Shakespeare 25
2 Dracula Stoker 15
3 1984 Orwell 18</code></pre>
<p>But for larger data frames, it’s best to use the <code>View()</code> function: <code>View(ebooks)</code>. You can also use <code>head()</code> to see a preview (in this particular case, the data frame is too small to preview).</p>
<p>All you Excel users might be wondering: how do I click in a cell and edit it?! R doesn’t work like that. If you want to manipulate values, it’s best to do it with an expression in the R console, and have all modifications documented in your script. We will be going into how to do these modifications next session. But if you insist, you can pull up a traditional point-and-click spreadsheet by using the <code>edit()</code> function: <code>edit(ebooks)</code>.</p>
</div>
<div id="exploring-data-frames" class="section level2">
<h2>Exploring data frames</h2>
<p>There are a number of ways to explore your data frame:</p>
<pre class="r"><code>#display information about the data frame
str(ebooks)
# dimensions: 3 rows, 3 columns
dim(ebooks)
## [1] 3 3
# number of rows
nrow(ebooks)
## [1] 3
# number of columns
ncol(ebooks)
## [1] 3
# column names
names(ebooks)
## [1] "title" "author" "checkouts"</code></pre>
<p>You can use the <code>$</code> symbol to work with particular variables.</p>
<pre class="r"><code>print(ebooks$title)
class(ebooks$title)
## [1] "character"
class(ebooks$checkouts)
## [1] "numeric"
# use summary() for more detail on a variable
summary(ebooks$checkouts)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 15.00 16.50 18.00 19.33 21.50 25.00 </code></pre>
<hr />
<p><strong>TRY IT YOURSELF</strong></p>
<ol style="list-style-type: decimal">
<li>Look at the help file for <code>state.name</code></li>
<li>Manually construct three vectors: <code>stateName</code>, <code>division</code>, and <code>area</code>.
<div data-pagedtable="false">
<script data-pagedtable-source type="application/json">
{"columns":[{"label":["stateName"],"name":[1],"type":["chr"],"align":["left"]},{"label":["division"],"name":[2],"type":["fct"],"align":["left"]},{"label":["area"],"name":[3],"type":["int"],"align":["right"]}],"data":[{"1":"Alaska","2":"Pacific","3":"590000"},{"1":"Arizona","2":"Mountain","3":"120000"},{"1":"California","2":"Pacific","3":"160000"},{"1":"Colorado","2":"Mountain","3":"110000"},{"1":"Montana","2":"Mountain","3":"150000"}],"options":{"columns":{"min":{},"max":[10]},"rows":{"min":[10],"max":[10]},"pages":{}}}
</script>
</div></li>
<li>Use <code>data.frame()</code> to create a data frame of these three vectors. Assign it to <code>myStates</code>. Remember to set <code>stringsAsFactors</code> to <code>FALSE</code></li>
<li>What is the <code>)</code> of each vector?</li>
<li>Using the <code>$</code> character, run <code>sum()</code> on the <code>area</code> variable. What is the sum area of these five states? What is the median?</li>
</ol>
</div>
</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",
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 = false;
// 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>