This repository has been archived by the owner on Aug 4, 2020. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 76
/
01-intro-to-R.html
696 lines (625 loc) · 40.9 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
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="pandoc" />
<meta name="author" content="Data Carpentry contributors" />
<title>Introduction to R</title>
<script src="site_libs/jquery-1.11.3/jquery.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="site_libs/bootstrap-3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<script src="site_libs/bootstrap-3.3.5/js/bootstrap.min.js"></script>
<script src="site_libs/bootstrap-3.3.5/shim/html5shiv.min.js"></script>
<script src="site_libs/bootstrap-3.3.5/shim/respond.min.js"></script>
<script src="site_libs/jqueryui-1.11.4/jquery-ui.min.js"></script>
<link href="site_libs/tocify-1.9.1/jquery.tocify.css" rel="stylesheet" />
<script src="site_libs/tocify-1.9.1/jquery.tocify.js"></script>
<script src="site_libs/navigation-1.1/tabsets.js"></script>
<link href="site_libs/font-awesome-5.0.13/css/fa-svg-with-js.css" rel="stylesheet" />
<script src="site_libs/font-awesome-5.0.13/js/fontawesome-all.min.js"></script>
<script src="site_libs/font-awesome-5.0.13/js/fa-v4-shims.min.js"></script>
<style type="text/css">code{white-space: pre;}</style>
<style type="text/css">
a.sourceLine { display: inline-block; line-height: 1.25; }
a.sourceLine { pointer-events: none; color: inherit; text-decoration: inherit; }
a.sourceLine:empty { height: 1.2em; position: absolute; }
.sourceCode { overflow: visible; }
code.sourceCode { white-space: pre; position: relative; }
div.sourceCode { margin: 1em 0; }
pre.sourceCode { margin: 0; }
@media screen {
div.sourceCode { overflow: auto; }
}
@media print {
code.sourceCode { white-space: pre-wrap; }
a.sourceLine { text-indent: -1em; padding-left: 1em; }
}
pre.numberSource a.sourceLine
{ position: relative; }
pre.numberSource a.sourceLine:empty
{ position: absolute; }
pre.numberSource a.sourceLine::before
{ content: attr(data-line-number);
position: absolute; left: -5em; text-align: right; vertical-align: baseline;
border: none; pointer-events: all;
-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 {
a.sourceLine::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 { } /* 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 { } /* 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>
<style type="text/css">
pre:not([class]) {
background-color: white;
}
</style>
<style type="text/css">
h1 {
font-size: 34px;
}
h1.title {
font-size: 38px;
}
h2 {
font-size: 30px;
}
h3 {
font-size: 24px;
}
h4 {
font-size: 18px;
}
h5 {
font-size: 16px;
}
h6 {
font-size: 12px;
}
.table th:not([align]) {
text-align: left;
}
</style>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<style type = "text/css">
.main-container {
max-width: 940px;
margin-left: auto;
margin-right: auto;
}
code {
color: inherit;
background-color: rgba(0, 0, 0, 0.04);
}
img {
max-width:100%;
height: auto;
}
.tabbed-pane {
padding-top: 12px;
}
.html-widget {
margin-bottom: 20px;
}
button.code-folding-btn:focus {
outline: none;
}
</style>
<style type="text/css">
/* padding for bootstrap navbar */
body {
padding-top: 51px;
padding-bottom: 40px;
}
/* offset scroll position for anchor links (for fixed navbar) */
.section h1 {
padding-top: 56px;
margin-top: -56px;
}
.section h2 {
padding-top: 56px;
margin-top: -56px;
}
.section h3 {
padding-top: 56px;
margin-top: -56px;
}
.section h4 {
padding-top: 56px;
margin-top: -56px;
}
.section h5 {
padding-top: 56px;
margin-top: -56px;
}
.section h6 {
padding-top: 56px;
margin-top: -56px;
}
</style>
<script>
// manage active state of menu based on current page
$(document).ready(function () {
// active menu anchor
href = window.location.pathname
href = href.substr(href.lastIndexOf('/') + 1)
if (href === "")
href = "index.html";
var menuAnchor = $('a[href="' + href + '"]');
// mark it active
menuAnchor.parent().addClass('active');
// if it's got a parent navbar menu mark it active as well
menuAnchor.closest('li.dropdown').addClass('active');
});
</script>
<div class="container-fluid main-container">
<!-- tabsets -->
<script>
$(document).ready(function () {
window.buildTabsets("TOC");
});
</script>
<!-- code folding -->
<script>
$(document).ready(function () {
// move toc-ignore selectors from section div to header
$('div.section.toc-ignore')
.removeClass('toc-ignore')
.children('h1,h2,h3,h4,h5').addClass('toc-ignore');
// establish options
var options = {
selectors: "h1,h2,h3",
theme: "bootstrap3",
context: '.toc-content',
hashGenerator: function (text) {
return text.replace(/[.\\/?&!#<>]/g, '').replace(/\s/g, '_').toLowerCase();
},
ignoreSelector: ".toc-ignore",
scrollTo: 0
};
options.showAndHide = false;
options.smoothScroll = true;
// tocify
var toc = $("#TOC").tocify(options).data("toc-tocify");
});
</script>
<style type="text/css">
#TOC {
margin: 25px 0px 20px 0px;
}
@media (max-width: 768px) {
#TOC {
position: relative;
width: 100%;
}
}
.toc-content {
padding-left: 30px;
padding-right: 40px;
}
div.main-container {
max-width: 1200px;
}
div.tocify {
width: 20%;
max-width: 260px;
max-height: 85%;
}
@media (min-width: 768px) and (max-width: 991px) {
div.tocify {
width: 25%;
}
}
@media (max-width: 767px) {
div.tocify {
width: 100%;
max-width: none;
}
}
.tocify ul, .tocify li {
line-height: 20px;
}
.tocify-subheader .tocify-item {
font-size: 0.90em;
padding-left: 25px;
text-indent: 0;
}
.tocify .list-group-item {
border-radius: 0px;
}
.tocify-subheader {
display: inline;
}
.tocify-subheader .tocify-item {
font-size: 0.95em;
}
</style>
<!-- setup 3col/9col grid for toc_float and main content -->
<div class="row-fluid">
<div class="col-xs-12 col-sm-4 col-md-3">
<div id="TOC" class="tocify">
</div>
</div>
<div class="toc-content col-xs-12 col-sm-8 col-md-9">
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.html"></a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>
<a href="index.html">Home</a>
</li>
<li>
<a href="00-before-we-start.html">Before we start</a>
</li>
<li>
<a href="01-intro-to-R.html">Intro to R</a>
</li>
<li>
<a href="02-starting-with-data.html">Starting with data</a>
</li>
<li>
<a href="03-data-frames.html">Data frames</a>
</li>
<li>
<a href="04-dplyr.html">The dplyr package</a>
</li>
<li>
<a href="05-data-visualization.html">Data visualization</a>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li>
<a href="https://github.com/data-lessons/R-genomics">
<span class="fa fa-github fa-lg"></span>
</a>
</li>
</ul>
</div><!--/.nav-collapse -->
</div><!--/.container -->
</div><!--/.navbar -->
<div class="fluid-row" id="header">
<h1 class="title toc-ignore">Introduction to R</h1>
<h4 class="author"><em>Data Carpentry contributors</em></h4>
</div>
<hr />
<blockquote>
<h2 id="learning-objectives">Learning Objectives</h2>
<ul>
<li>Assign names to objects in R with <- and =.</li>
<li>Solve mathematical operations in R.</li>
<li>Describe what a function is in R.</li>
<li>Describe what vectors are and how they can be manipulated in R.</li>
<li>Inspect the content of vectors in R and describe their content with class and str.</li>
</ul>
</blockquote>
<hr />
<div id="the-r-syntax" class="section level2">
<h2>The R syntax</h2>
<p><em>Start by showing an example of a script</em></p>
<ul>
<li>Point to the different parts:
<ul>
<li>a function</li>
<li>the assignment operator <code><-</code></li>
<li>the <code>=</code> for arguments</li>
<li>the comments <code>#</code> and how they are used to document function and its content</li>
<li>the <code>$</code> operator</li>
</ul></li>
<li>Point to indentation and consistency in spacing to improve clarity</li>
</ul>
</div>
<div id="creating-objects" class="section level2">
<h2>Creating objects</h2>
<p>You can get an output from R simply by typing in math in the console</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb1-1" data-line-number="1"><span class="dv">3</span> <span class="op">+</span><span class="st"> </span><span class="dv">5</span></a>
<a class="sourceLine" id="cb1-2" data-line-number="2"><span class="dv">12</span><span class="op">/</span><span class="dv">7</span></a></code></pre></div>
<p>We can also comment on what it is that we’re doing</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb2-1" data-line-number="1"><span class="co"># I'm adding 3 and 5. R is fun!</span></a>
<a class="sourceLine" id="cb2-2" data-line-number="2"><span class="dv">3</span><span class="op">+</span><span class="dv">5</span></a></code></pre></div>
<p>What happens if we type that same command without the # sign in the front?</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb3-1" data-line-number="1">I<span class="st">'m adding 3 and 5. R is fun!</span></a>
<a class="sourceLine" id="cb3-2" data-line-number="2"><span class="st">3+5</span></a></code></pre></div>
<p>Now R is trying to run that sentence as a command, and it doesn’t work. Now we’re stuck over in the console. The <code>+</code> sign means that it’s still waiting for input, so we can’t type in a new command. To get out of this press the <kbd>Esc</kbd> key. This will work whenever you’re stuck with that <code>+</code> sign.</p>
<p>It’s great that R is a glorified caluculator, but obviously we want to do more interesting things.</p>
<p>To do useful and interesting things, we need to assign <em>values</em> to <em>objects</em>. To create objects, we need to give it a name followed by the assignment operator <code><-</code> and the value we want to give it.</p>
<p>For instance, instead of adding 3 + 5, we can assign those values to objects and then add them.</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb4-1" data-line-number="1"><span class="co"># assign 3 to a</span></a>
<a class="sourceLine" id="cb4-2" data-line-number="2">a <-<span class="st"> </span><span class="dv">3</span></a>
<a class="sourceLine" id="cb4-3" data-line-number="3"><span class="co"># assign 5 to b</span></a>
<a class="sourceLine" id="cb4-4" data-line-number="4">b <-<span class="st"> </span><span class="dv">5</span></a>
<a class="sourceLine" id="cb4-5" data-line-number="5"></a>
<a class="sourceLine" id="cb4-6" data-line-number="6"><span class="co"># what now is a</span></a>
<a class="sourceLine" id="cb4-7" data-line-number="7">a</a>
<a class="sourceLine" id="cb4-8" data-line-number="8"><span class="co"># what now is b</span></a>
<a class="sourceLine" id="cb4-9" data-line-number="9">b</a>
<a class="sourceLine" id="cb4-10" data-line-number="10"></a>
<a class="sourceLine" id="cb4-11" data-line-number="11"><span class="co">#Add a and b</span></a>
<a class="sourceLine" id="cb4-12" data-line-number="12">a <span class="op">+</span><span class="st"> </span>b</a></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>. You can also use <code>=</code> or <code>-></code>for assignments but not in all contexts so it is good practice to use <code><-</code> for assignments. <code>=</code> should only be used to specify the values of arguments in functions, see below.</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.</p>
<div id="exercise" class="section level3">
<h3>Exercise</h3>
<ul>
<li>What happens if we change <code>a</code> and then re-add <code>a</code> and <code>b</code>?</li>
<li>Does it work if you just change <code>a</code> in the script and then add <code>a</code> and <code>b</code>? Did you still get the same answer after they changed <code>a</code>? If so, why do you think that might be?</li>
<li>We can also assign a + b to a new variable, <code>c</code>. How would you do this?</li>
</ul>
</div>
</div>
<div id="notes-on-objects" class="section level2">
<h2>Notes on objects</h2>
<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>Genome_length_mb</code> is different from <code>genome_length_mb</code>). There are some names that cannot be used because they represent 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>). When in doubt, check the help to see if the name is already in use. It’s also best to avoid dots (<code>.</code>) within a variable 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 variable 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 variables, etc.). In R, two popular style guides are <a href="http://adv-r.had.co.nz/Style.html">Hadley Wickham’s</a> and <a href="https://google.github.io/styleguide/Rguide.xml">Google’s</a>.</p>
<p>When assigning a value to an object, R does not print anything. You can force to print the value by using parentheses or by typing the name:</p>
<div class="sourceCode" id="cb5"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb5-1" data-line-number="1"><span class="co"># Assigns a value to a variable</span></a>
<a class="sourceLine" id="cb5-2" data-line-number="2">genome_size_mb <-<span class="st"> </span><span class="dv">35</span></a>
<a class="sourceLine" id="cb5-3" data-line-number="3"></a>
<a class="sourceLine" id="cb5-4" data-line-number="4"><span class="co"># Assigns a value to a variable and prints it out on the console</span></a>
<a class="sourceLine" id="cb5-5" data-line-number="5">(genome_size_mb <-<span class="st"> </span><span class="dv">35</span>)</a>
<a class="sourceLine" id="cb5-6" data-line-number="6"></a>
<a class="sourceLine" id="cb5-7" data-line-number="7"><span class="co"># Prints out the value of a variable on the console</span></a>
<a class="sourceLine" id="cb5-8" data-line-number="8">genome_size_mb</a></code></pre></div>
</div>
<div id="functions" class="section level2">
<h2>Functions</h2>
<p>The other key feature of R are functions. These are R’s built in capabilities. Some examples of these are mathematical functions, like <code>sqrt</code> and <code>round</code>. You can also get functions from libraries (which we’ll talk about in a bit), or even write your own.</p>
<p>Functions are “canned scripts” that automate something complicated or convenient or both. Many functions are predefined, or become available when using the function <code>library()</code> (more on that later). A function usually gets 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>
<p><code>sqrt(a)</code></p>
<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. 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 data set. We’ll see that when we read data files in to 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). If an argument alters the way the function operates, such as whether to ignore ‘bad values’, such an argument is sometimes called an <em>option</em>.</p>
<p>Most functions can take several arguments, but many have so-called <em>defaults</em>. If you don’t specify such an argument when calling the function, the function itself will fall back on using the <em>default</em>. This is a standard value that the author of the function specified as being “good enough in standard cases”. An example would be what symbol to use in a plot. However, if you want something specific, simply change the argument yourself with a value of your choice.</p>
<p>Let’s try a function that can take multiple arguments <code>round</code>.</p>
<div class="sourceCode" id="cb6"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb6-1" data-line-number="1"><span class="kw">round</span>(<span class="fl">3.14159</span>)</a></code></pre></div>
<pre><code>## [1] 3</code></pre>
<p>We can see that we get <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> or look at the help for this function using <code>?round</code>.</p>
<div class="sourceCode" id="cb8"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb8-1" data-line-number="1"><span class="kw">args</span>(round)</a></code></pre></div>
<pre><code>## function (x, digits = 0)
## NULL</code></pre>
<div class="sourceCode" id="cb10"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb10-1" data-line-number="1">?round</a></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="cb11"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb11-1" data-line-number="1"><span class="kw">round</span>(<span class="fl">3.14159</span>, <span class="dt">digits=</span><span class="dv">2</span>)</a></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="cb13"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb13-1" data-line-number="1"><span class="kw">round</span>(<span class="fl">3.14159</span>, <span class="dv">2</span>)</a></code></pre></div>
<pre><code>## [1] 3.14</code></pre>
<p>However, it’s usually not recommended practice because it’s a lot of remembering to do, and if you share your code with others that includes less known functions it makes your code difficult to read. (It’s however OK to not include the names of the arguments for basic functions like <code>mean</code>, <code>min</code>, etc…)</p>
<p>Another advantage of naming arguments, is that the order doesn’t matter. This is useful when there start to be more arguments.</p>
<div id="exercise-1" class="section level3">
<h3>Exercise</h3>
<p>We’re going to work with genome lengths. - Create a variable <code>genome_length_mb</code> and assign it the value <code>4.6</code></p>
<div id="solution" class="section level4">
<h4>Solution</h4>
<div class="sourceCode" id="cb15"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb15-1" data-line-number="1">genome_length_mb <-<span class="st"> </span><span class="fl">4.6</span></a>
<a class="sourceLine" id="cb15-2" data-line-number="2">genome_length_mb</a></code></pre></div>
</div>
</div>
<div id="exercise-2" class="section level3">
<h3>Exercise</h3>
<p>Now that R has <code>genome_length_mb</code> in memory, we can do arithmetic with it. For instance, we may want to convert this to the weight of the genome in picograms (for some reason). 978Mb = 1picogram. Divide the genome length in Mb by 978.</p>
<div id="solution-1" class="section level4">
<h4>Solution</h4>
<div class="sourceCode" id="cb16"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb16-1" data-line-number="1">genome_length_mb <span class="op">/</span><span class="st"> </span><span class="fl">978.0</span></a></code></pre></div>
<p>It turns out an E. coli genome doesn’t weigh very much.</p>
</div>
</div>
<div id="exercise-3" class="section level3">
<h3>Exercise</h3>
<p>We can also change the variable’s value by assigning it a new one. Say we want to think about a human genome rather than E. coli. Change <code>genome_length_mb</code> to 3000 and figure out the weight of the human genome.</p>
<div id="solution-2" class="section level4">
<h4>Solution</h4>
<div class="sourceCode" id="cb17"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb17-1" data-line-number="1">genome_length_mb <-<span class="st"> </span><span class="fl">3000.0</span></a>
<a class="sourceLine" id="cb17-2" data-line-number="2">genome_length_mb <span class="op">/</span><span class="st"> </span><span class="fl">978.0</span></a></code></pre></div>
<p>This means that assigning a value to one variable does not change the values of other variables. For example, let’s store the genome’s weight in a variable.</p>
<div class="sourceCode" id="cb18"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb18-1" data-line-number="1">genome_weight_pg <-<span class="st"> </span>genome_length_mb <span class="op">/</span><span class="st"> </span><span class="fl">978.0</span></a></code></pre></div>
<p>and then change <code>genome_length_mb</code> to 100.</p>
<div class="sourceCode" id="cb19"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb19-1" data-line-number="1">genome_length_mb <-<span class="st"> </span><span class="dv">100</span></a></code></pre></div>
</div>
</div>
<div id="exercise-4" class="section level3">
<h3>Exercise</h3>
<p>What do you think is the current content of the object <code>genome_weight_pg</code>? 3.06 or 0.102?</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 structure in R, and is pretty much the workhorse of R. It’s basically just a list of values, mainly either numbers or characters. They’re special lists that you can do math with. You can assign this list of values to a variable, just like you would for one item. For example we can create a vector of genome lengths:</p>
<div class="sourceCode" id="cb20"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb20-1" data-line-number="1">glengths <-<span class="st"> </span><span class="kw">c</span>(<span class="fl">4.6</span>, <span class="dv">3000</span>, <span class="dv">50000</span>)</a>
<a class="sourceLine" id="cb20-2" data-line-number="2">glengths</a></code></pre></div>
<p>A vector can also contain characters:</p>
<div class="sourceCode" id="cb21"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb21-1" data-line-number="1">species <-<span class="st"> </span><span class="kw">c</span>(<span class="st">"ecoli"</span>, <span class="st">"human"</span>, <span class="st">"corn"</span>)</a>
<a class="sourceLine" id="cb21-2" data-line-number="2">species</a></code></pre></div>
<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="cb22"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb22-1" data-line-number="1"><span class="kw">length</span>(glengths)</a>
<a class="sourceLine" id="cb22-2" data-line-number="2"><span class="kw">length</span>(species)</a></code></pre></div>
<p>You can also do math with whole vectors. For instance if we wanted to multiply the genome lengths of all the genomes in the list, we can do</p>
<div class="sourceCode" id="cb23"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb23-1" data-line-number="1"><span class="dv">5</span> <span class="op">*</span><span class="st"> </span>glengths</a></code></pre></div>
<p>or we can add the data in the two vectors together</p>
<div class="sourceCode" id="cb24"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb24-1" data-line-number="1">new_lengths <-<span class="st"> </span>glengths <span class="op">+</span><span class="st"> </span>glengths</a>
<a class="sourceLine" id="cb24-2" data-line-number="2">new_lengths</a></code></pre></div>
<p>This is very useful if we have data in different vectors that we want to combine or work with.</p>
<p>There are few ways to figure out what’s going on in a vector.</p>
<p><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"><a class="sourceLine" id="cb25-1" data-line-number="1"><span class="kw">class</span>(glengths)</a>
<a class="sourceLine" id="cb25-2" data-line-number="2"><span class="kw">class</span>(species)</a></code></pre></div>
<p>The function <code>str()</code> provides an overview of the object and the elements it contains. It is a really useful function when working with large and complex objects:</p>
<div class="sourceCode" id="cb26"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb26-1" data-line-number="1"><span class="kw">str</span>(glengths)</a>
<a class="sourceLine" id="cb26-2" data-line-number="2"><span class="kw">str</span>(species)</a></code></pre></div>
<p>You can add elements to your vector simply by using the <code>c()</code> function:</p>
<div class="sourceCode" id="cb27"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb27-1" data-line-number="1">lengths <-<span class="st"> </span><span class="kw">c</span>(glengths, <span class="dv">90</span>) <span class="co"># adding at the end</span></a>
<a class="sourceLine" id="cb27-2" data-line-number="2">lengths <-<span class="st"> </span><span class="kw">c</span>(<span class="dv">30</span>, glengths) <span class="co"># adding at the beginning</span></a>
<a class="sourceLine" id="cb27-3" data-line-number="3">lengths</a></code></pre></div>
<p>What happens here is that we take the original vector <code>glengths</code>, and we are adding another item first to the end of the other ones, and then another item at the beginning. We can do this over and over again to build a vector or a dataset. As we program, this may be useful to autoupdate results that we are collecting or calculating.</p>
<p>We just saw 2 of the 6 <strong>data types</strong> that R uses: <code>"character"</code> and <code>"numeric"</code>. The other 4 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> that we won’t discuss further</li>
</ul>
<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>) and factors (<code>factor</code>).</p>
</div>
<div id="seeking-help" class="section level2">
<h2>Seeking help</h2>
<div id="i-know-the-name-of-the-function-i-want-to-use-but-im-not-sure-how-to-use-it" class="section level3">
<h3>I know the name of the function I want to use, but I’m not sure how to use it</h3>
<p>If you need help with a specific function, let’s say <code>barplot()</code>, you can type:</p>
<div class="sourceCode" id="cb28"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb28-1" data-line-number="1">?barplot</a></code></pre></div>
<p>If you just need to remind yourself of the names of the arguments, you can use:</p>
<div class="sourceCode" id="cb29"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb29-1" data-line-number="1"><span class="kw">args</span>(lm)</a></code></pre></div>
<p>If the function is part of a package that is installed on your computer but don’t remember which one, you can type:</p>
<div class="sourceCode" id="cb30"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb30-1" data-line-number="1">??geom_point</a></code></pre></div>
</div>
<div id="i-want-to-use-a-function-that-does-x-there-must-be-a-function-for-it-but-i-dont-know-which-one" class="section level3">
<h3>I want to use a function that does X, there must be a function for it but I don’t know which one…</h3>
<p>If you are looking for a function to do a particular task, you can use <code>help.search()</code> (but only looks through the installed packages):</p>
<div class="sourceCode" id="cb31"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb31-1" data-line-number="1"><span class="kw">help.search</span>(<span class="st">"kruskal"</span>)</a></code></pre></div>
<p>If you can’t find what you are looking for, you can use the <a href="http://www.rdocumentation.org">rdocumention.org</a> website that search through the help files across all packages available.</p>
</div>
<div id="i-am-stuck-i-get-an-error-message-that-i-dont-understand" class="section level3">
<h3>I am stuck… I get an error message that I don’t understand</h3>
<p>Start by googling the error message. However, this doesn’t always work very well because often, package developers rely on the error catching provided by R. You end up with general error messages that might not be very helpful to diagnose a problem (e.g. “subscript out of bounds”).</p>
<p>However, you should check <a href="https://stackoverflow.com">stackoverflow.com</a>. Search using the <code>[r]</code> tag. Most questions have already been answered, but the challenge is to use the right words in the search to find the answers: <a href="http://stackoverflow.com/questions/tagged/r" class="uri">http://stackoverflow.com/questions/tagged/r</a></p>
<p>The <a href="http://cran.r-project.org/doc/manuals/R-intro.pdf">Introduction to R</a> can also be dense for people with little programming experience but it is a good place to understand the underpinnings of the R language.</p>
<p>The <a href="http://cran.r-project.org/doc/FAQ/R-FAQ.html">R FAQ</a> is dense and technical but it is full of useful information.</p>
</div>
<div id="asking-for-help" class="section level3">
<h3>Asking for help</h3>
<p>The key to get help from someone is for them to grasp your problem rapidly. You should make it as easy as possible to pinpoint where the issue might be.</p>
<p>Try to use the correct words to describe your problem. For instance, a package is not the same thing as a library. Most people will understand what you meant, but others have really strong feelings about the difference in meaning. The key point is that it can make things confusing for people trying to help you. Be as precise as possible when describing your problem</p>
<p>If possible, try to reduce what doesn’t work to a simple reproducible example. If you can reproduce the problem using a very small <code>data.frame</code> instead of your 50,000 rows and 10,000 columns one, provide the small one with the description of your problem. When appropriate, try to generalize what you are doing so even people who are not in your field can understand the question.</p>
<p>To share an object with someone else, if it’s relatively small, you can use the function <code>dput()</code>. It will output R code that can be used to recreate the exact same object as the one in memory:</p>
<div class="sourceCode" id="cb32"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb32-1" data-line-number="1"><span class="kw">dput</span>(<span class="kw">head</span>(iris)) <span class="co"># iris is an example data.frame that comes with R</span></a></code></pre></div>
<pre><code>## structure(list(Sepal.Length = c(5.1, 4.9, 4.7, 4.6, 5, 5.4),
## Sepal.Width = c(3.5, 3, 3.2, 3.1, 3.6, 3.9), Petal.Length = c(1.4,
## 1.4, 1.3, 1.5, 1.4, 1.7), Petal.Width = c(0.2, 0.2, 0.2,
## 0.2, 0.2, 0.4), Species = structure(c(1L, 1L, 1L, 1L, 1L,
## 1L), .Label = c("setosa", "versicolor", "virginica"), class = "factor")), row.names = c(NA,
## 6L), class = "data.frame")</code></pre>
<p>If the object is larger, provide either the raw file (i.e., your CSV file) with your script up to the point of the error (and after removing everything that is not relevant to your issue). Alternatively, in particular if your questions is not related to a <code>data.frame</code>, you can save any R object to a file. Note: for this example, the folder “/tmp” needs to already exist.</p>
<div class="sourceCode" id="cb34"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb34-1" data-line-number="1"><span class="kw">saveRDS</span>(iris, <span class="dt">file=</span><span class="st">"/tmp/iris.rds"</span>)</a></code></pre></div>
<p>The content of this file is however not human readable and cannot be posted directly on stackoverflow. It can however be sent to someone by email who can read it with this command:</p>
<div class="sourceCode" id="cb35"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb35-1" data-line-number="1">some_data <-<span class="st"> </span><span class="kw">readRDS</span>(<span class="dt">file=</span><span class="st">"~/Downloads/iris.rds"</span>)</a></code></pre></div>
<p>Last, but certainly not least, <strong>always include the output of <code>sessionInfo()</code></strong> as it provides critical information about your platform, the versions of R and the packages that you are using, and other information that can be very helpful to understand your problem.</p>
<div class="sourceCode" id="cb36"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb36-1" data-line-number="1"><span class="kw">sessionInfo</span>()</a></code></pre></div>
<pre><code>## R version 3.5.1 (2018-07-02)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 18.10
##
## Matrix products: default
## BLAS: /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.8.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.8.0
##
## locale:
## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C
## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8
## [5] LC_MONETARY=en_US.UTF-8 LC_MESSAGES=en_US.UTF-8
## [7] LC_PAPER=en_US.UTF-8 LC_NAME=C
## [9] LC_ADDRESS=C LC_TELEPHONE=C
## [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C
##
## attached base packages:
## [1] stats graphics grDevices utils datasets methods base
##
## other attached packages:
## [1] BiocInstaller_1.30.0
##
## loaded via a namespace (and not attached):
## [1] compiler_3.5.1 backports_1.1.2 magrittr_1.5 rprojroot_1.3-2
## [5] tools_3.5.1 htmltools_0.3.6 yaml_2.2.0 Rcpp_0.12.19
## [9] stringi_1.2.4 rmarkdown_1.10 knitr_1.20 stringr_1.3.1
## [13] digest_0.6.18 evaluate_0.12</code></pre>
</div>
<div id="where-to-ask-for-help" class="section level3">
<h3>Where to ask for help?</h3>
<ul>
<li>Your friendly colleagues: if you know someone with more experience than you, they might be able and willing to help you.</li>
<li>Stackoverflow: if your question hasn’t been answered before and is well crafted, chances are you will get an answer in less than 5 min.</li>
<li>The <a href="https://stat.ethz.ch/mailman/listinfo/r-help">R-help</a>: it is read by a lot of people (including most of the R core team), a lot of people post to it, but the tone can be pretty dry, and it is not always very welcoming to new users. If your question is valid, you are likely to get an answer very fast but don’t expect that it will come with smiley faces. Also, here more than everywhere else, be sure to use correct vocabulary (otherwise you might get an answer pointing to the misuse of your words rather than answering your question). You will also have more success if your question is about a base function rather than a specific package.</li>
<li>If your question is about a specific package, see if there is a mailing list for it. Usually it’s included in the DESCRIPTION file of the package that can be accessed using <code>packageDescription("name-of-package")</code>. You may also want to try to email the author of the package directly.</li>
<li>There are also some topic-specific mailing lists (GIS, phylogenetics, etc…), the complete list is <a href="http://www.r-project.org/mail.html">here</a>.</li>
</ul>
</div>
<div id="more-resources" class="section level3">
<h3>More resources</h3>
<ul>
<li>The <a href="http://www.r-project.org/posting-guide.html">Posting Guide</a> for the R mailing lists.</li>
<li><a href="http://blog.revolutionanalytics.com/2014/01/how-to-ask-for-r-help.html">How to ask for R help</a> useful guidelines</li>
</ul>
</div>
</div>
<hr/>
<p><a href="http://datacarpentry.org/">Data Carpentry</a>,
2017-2018. <a href="LICENSE.html">License</a>. <a href="CONTRIBUTING.html">Contributing</a>. <br/>
Questions? Feedback?
Please <a href="https://github.com/datacarpentry/R-genomics/issues/new">file
an issue on GitHub</a>. <br/> On
Twitter: <a href="https://twitter.com/datacarpentry">@datacarpentry</a></p>
</div>
</div>
</div>
<script>
// add bootstrap table styles to pandoc tables
function bootstrapStylePandocTables() {
$('tr.header').parent('thead').parent('table').addClass('table table-condensed');
}
$(document).ready(function () {
bootstrapStylePandocTables();
});
</script>
<!-- dynamically load mathjax for compatibility with self-contained -->
<script>
(function () {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML";
document.getElementsByTagName("head")[0].appendChild(script);
})();
</script>
</body>
</html>