-
Notifications
You must be signed in to change notification settings - Fork 0
/
Baby_steps.html
567 lines (496 loc) · 27.6 KB
/
Baby_steps.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
<!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="Stuart Demmer" />
<meta name="date" content="2018-07-28" />
<title>Baby steps</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/flatly.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/highlightjs-9.12.0/default.css" rel="stylesheet" />
<script src="site_libs/highlightjs-9.12.0/highlight.js"></script>
<style type="text/css">code{white-space: pre;}</style>
<style type="text/css">
pre:not([class]) {
background-color: white;
}
</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>
<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>
</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: 60px;
padding-bottom: 40px;
}
/* offset scroll position for anchor links (for fixed navbar) */
.section h1 {
padding-top: 65px;
margin-top: -65px;
}
.section h2 {
padding-top: 65px;
margin-top: -65px;
}
.section h3 {
padding-top: 65px;
margin-top: -65px;
}
.section h4 {
padding-top: 65px;
margin-top: -65px;
}
.section h5 {
padding-top: 65px;
margin-top: -65px;
}
.section h6 {
padding-top: 65px;
margin-top: -65px;
}
</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,h4",
theme: "bootstrap3",
context: '.toc-content',
hashGenerator: function (text) {
return text.replace(/[.\\/?&!#<>]/g, '').replace(/\s/g, '_').toLowerCase();
},
ignoreSelector: ".toc-ignore",
scrollTo: 0
};
options.showAndHide = true;
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;
}
</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-inverse 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">SAEON GSN R intro workshop</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>
<a href="Introduction.html">Intro</a>
</li>
<li>
<a href="Baby_steps.html">Baby steps</a>
</li>
<li>
<a href="Data_wrangling.html">Data wrangling</a>
</li>
<li>
<a href="Data_visualisation.html">Data vis</a>
</li>
<li>
<a href="Statistics_intro.html">Stats intro</a>
</li>
<li>
<a href="Multivariate.html">Multivariate</a>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
</ul>
</div><!--/.nav-collapse -->
</div><!--/.container -->
</div><!--/.navbar -->
<div class="fluid-row" id="header">
<h1 class="title toc-ignore">Baby steps</h1>
<h4 class="author"><em>Stuart Demmer</em></h4>
<h4 class="date"><em>28 July 2018</em></h4>
</div>
<script>
$(document).ready(function() {
$items = $('div#TOC li');
$items.each(function(idx) {
num_ul = $(this).parentsUntil('#TOC').length;
$(this).css({'text-indent': num_ul * 10, 'padding-left': 0});
});
});
</script>
<div id="how-to-speak-r" class="section level1">
<h1>How to speak R</h1>
<div id="creating-objects-in-r" class="section level2">
<h2>Creating objects in R</h2>
<p>We just learnt about the differences between the console and scripts and also we commanded R to carry out some simple (and not so simple) analyses for us. For a bit of a recap type <code>3 + 5</code> into the console. This is cool but has major limitations. If we wanted to add that answer to 10 we would have to repeate the process by going <code>3 + 5 + 10</code>. None of what we did was ‘stored’ anywhere. This is where R becomes even more useful. We can assign <em>values</em> to <em>objects</em>. Let’s suppose we have two people, one of whom has three apples and another who has five apples. We can then command R to store the sum of all the apples by coding <code>apples.sum <- 3 + 5</code> - who would have thought you would have to do story sums after grade three!?</p>
<pre class="r"><code>3 + 5</code></pre>
<pre><code>## [1] 8</code></pre>
<pre class="r"><code>3 + 5 + 10</code></pre>
<pre><code>## [1] 18</code></pre>
<pre class="r"><code>apples.sum <- 3 + 5</code></pre>
<p>See how the answer for each command appears directly below it? But what about the last set of commands? Why do we not see 8 anywhere there? That’s because all we have told R to do is to store the sum of 3 + 5 in <code>apples.sum</code>. We haven’t told R to tell us what <code>apples.sum</code> equals to. But look here:</p>
<pre class="r"><code>apples.sum <- 3 + 5
apples.sum</code></pre>
<pre><code>## [1] 8</code></pre>
<p>We have told R that <code>apples.sum</code>‘s value is 3 + 5 and then we have told it to tell us what <code>apples.sum</code>’s value is! This is great! Now maybe we know that the person with three apples’ name is John (<code>John <- 3</code>) and the second person who has five apples’ name is Thandeka (<code>Thandeka <- 5</code>) we could get the sum of the apples by coding <code>apples.sum <- John + Thandeka</code>:</p>
<pre class="r"><code>John <- 3
Thandeka <- 5
apples.sum <- John + Thandeka
apples.sum</code></pre>
<pre><code>## [1] 8</code></pre>
<p>Neat hey? There is a lot going on here but break it down into its basic algebra and it should become easier to understand. The only really new thing is <code><-</code> which is called the “assignment operator”. Its job is to assign the <em>values</em> on the right into the <em>object</em> on the left. You can type this quickly in RStudio by typing <code>Alt</code> + <code>-</code> (pushing <code>Alt</code> at the same time as the <code>-</code> (minus) key).</p>
</div>
<div id="objects-and-variables" class="section level2">
<h2>Objects and variables</h2>
<p>On the surface there is little difference between these two terms. What are commonly called variables in other coding languages seem to be referred to as objects in R. The terms can be used interchangably for most instances in R, however, when dealing with statistical terminology, variables carry the same meaning in R as in general statistics.</p>
<p>Objects can be given almost any name but there are some important guidelines and considerations. The text below is taken from an <a href="http://r4ds.had.co.nz/workflow-basics.html#whats-in-a-name">R for Data Science</a> section:</p>
<blockquote>
<h4 id="whats-in-a-name">4.2 What’s in a name?</h4>
<p>Object names must start with a letter, and can only contain letters, numbers, <code>_</code> and <code>.</code>. You want your object names to be descriptive, so you’ll need a convention for multiple words. I recommend snake_case where you separate lowercase words with <code>_</code>.</p>
<p><code>i_use_snake_case</code><br />
<code>otherPeopleUseCamelCase</code><br />
<code>some.people.use.periods</code><br />
<code>And_aFew.People_RENOUNCEconvention</code><br />
<code>We’ll come back to code style later, in functions.</code></p>
<p>You can inspect an object by typing its name:</p>
<p><code>x</code> <code>#> [1] 12</code><br />
Make another assignment:</p>
<p><code>this_is_a_really_long_name <- 2.5</code> To inspect this object, try out RStudio’s completion facility: type “this”, press <code>TAB</code>, add characters until you have a unique prefix, then press return.</p>
<p>Ooops, you made a mistake! <code>this_is_a_really_long_name</code> should have value <code>3.5</code> not <code>2.5</code>. Use another keyboard shortcut to help you fix it. Type “this” then press <code>Ctrl</code> + <code>↑</code>. That will list all the commands you’ve typed that start those letters. Use the arrow keys to navigate, then press enter to retype the command. Change <code>2.5</code> to <code>3.5</code> and rerun.</p>
<p>Make yet another assignment:</p>
<p><code>r_rocks <- 2 ^ 3</code><br />
Let’s try to inspect it:</p>
<p><code>r_rock</code><br />
<code>#> Error: object 'r_rock' not found</code><br />
<code>R_rocks</code><br />
<code>#> Error: object 'R_rocks' not found</code><br />
There’s an implied contract between you and R: it will do the tedious computation for you, but in return, you must be completely precise in your instructions. Typos matter. Case matters.</p>
</blockquote>
<p>In general you should note that:</p>
<ul>
<li><p>Objects cannot start with a number</p></li>
<li><p>Objects cannot carry the same name as some basic R functions (e.g., <code>if</code>, <code>else</code>, <code>for</code>) and it is best not to use the names of other less fundamental functions (e.g., <code>c</code>, <code>T</code>, <code>mean</code>, <code>data</code>, <code>df</code>, <code>weights</code>).</p></li>
<li><p>As R is a dynamic language it is best to use nouns for object names and verbs for function names.</p></li>
<li><p>Be consistant with how you name your variables. There are several <em>style guides</em> available online which dictate how you should format your code and name your objects and functions.</p></li>
<li><p>The <a href="http://style.tidyverse.org/">tidyverse</a> style</p></li>
<li><p>The <a href="http://jef.works/R-style-guide/">Jean Fan</a> style</p></li>
<li><p>The <a href="https://google.github.io/styleguide/Rguide.xml">Google</a> style</p></li>
</ul>
<p>These might all seem overwhelming but it is good practice to adopt one of these and use it consistantly. The most popular one is the tidyverse style. RStudio also has addin capabilities for installing <a href="https://support.rstudio.com/hc/en-us/articles/205753617-Code-Diagnostics"><em>style checkers</em></a> or <em>style formatters</em> to correct your styling and suggest alternatives.</p>
</div>
<div id="back-to-coding" class="section level2">
<h2>Back to coding!</h2>
<p>We learnt that algebra works in R but that there are some slight differences, especially regarding the value assignment functionality. We can command R to both assign a value to an object and print the object’s value by enclosing the command in parentheses <code>()</code>:</p>
<pre class="r"><code>John <- 3 # doesn't print anything
Thandeka <- 5 # doesn't print anything
(apples.sum <- John + Thandeka) # but this does!</code></pre>
<pre><code>## [1] 8</code></pre>
<p>Objects can have their values manipulated or overwritten by either applying simple arithmatic to it or by assigning a new value to it:</p>
<pre class="r"><code>apples.sum # print current value of apples.sum</code></pre>
<pre><code>## [1] 8</code></pre>
<pre class="r"><code>apples.sum * 2 # compute and print the product of apples.sum and 2</code></pre>
<pre><code>## [1] 16</code></pre>
<pre class="r"><code>(apples.sum.2 <- apples.sum * 2) # compute, store in a new object and print the product of apples.sum and 2</code></pre>
<pre><code>## [1] 16</code></pre>
</div>
<div id="comments" class="section level2">
<h2>Comments</h2>
<p>Sometimes R code can get confusing to follow (both for you and someone else) and so it is important to describe exactly what you are doing as you do it. That is where comments come in. Comments are text which is stored in your script but do not affect the code’s output You can use comments to describe the code or you can comment out sections of code within a script that you do not want to run - this is useful for troubleshooting pesky code. To do this you can select the body of text and then push <code>Ctrl</code> + <code>Shift</code> + <code>c</code>.</p>
</div>
<div id="functions-and-their-arguments" class="section level2">
<h2>Functions and their arguments</h2>
<p>Functions are the heart of what makes programming so effective. Functions are essentially scripts which other people (and eventually maybe yourself) have written which consist of a set of commands which help carry out a particular task. ‘Base R’ contains some fundamental functions but more specific functions can be accessed by installing various other R packages. Functions usually get one or more inputs. These are called <em>arguments</em>. If the supplied <em>arguments</em> are correct then the function will generally return a value (or an array of many values) which can either be displayed immediately or assigned to an object for future reference. Let us look at the <code>sqrt()</code> function as an example. Call up the help file for this function by typing <code>?sqrt</code> into the console and pushing <code>Enter</code>. See how it shows <code>sqrt(x)</code> where under the <strong>Arguments</strong> section <code>x</code> is <code>a numeric or complex vector or array</code>? That basically means that <code>sqrt()</code> needs a numeric input:</p>
<pre class="r"><code>sqrt(4) # this works nicely</code></pre>
<pre><code>## [1] 2</code></pre>
<pre class="r"><code>a <- "a" # make a equal the letter "a"
sqrt(a) # this doesn't...</code></pre>
<pre><code>## Error in sqrt(a): non-numeric argument to mathematical function</code></pre>
<pre class="r"><code>a <- 4 # make a = 4
sqrt(a) # this should work now</code></pre>
<pre><code>## [1] 2</code></pre>
<p><code>sqrt()</code> is a fairly simple function in that it only accepts one argument. Many functions can accept (and require) more than just one argument. A simple one we can look at is <code>round()</code>. This rounds a numeric value to a defined number of decimal places. Typing <code>args()</code> lets you see what the arguments for a particular function are. If we type</p>
<pre class="r"><code>args(round)</code></pre>
<pre><code>## function (x, digits = 0)
## NULL</code></pre>
<p>we’ll see that <code>round()</code> accepts <code>x</code> and <code>digits =</code>. Again, <code>x</code> is a numeric vector or array. <code>digits =</code> refers to the number of decimal places you want after the point. You will see that the default value will often be defined. That means that you do not need to supply every argument but you can override the default arguments if you have the need to:</p>
<pre class="r"><code>a <- pi # a = pi = 3.14159
round(a) # round a off to the default number of digits</code></pre>
<pre><code>## [1] 3</code></pre>
<pre class="r"><code>round(a, digits = 3) # override the default number of digits to display the rounding to three places.</code></pre>
<pre><code>## [1] 3.142</code></pre>
<pre class="r"><code>round(digits = 3, x = a) # if you want to you can change the order of the arguments. This doesn't affect the function call at all.</code></pre>
<pre><code>## [1] 3.142</code></pre>
<pre class="r"><code>round(a,3) # if you do not define the argument values the function will default to its supplied order</code></pre>
<pre><code>## [1] 3.142</code></pre>
<pre class="r"><code>round(3,a) # not explicityly defining the arguments is a bad idea...</code></pre>
<pre><code>## [1] 3</code></pre>
<p>Be sure to correctly define your arguments when dealing with more complicated functions. You can save yourself and the people reading your code a lot of trouble if you do. Each function does, however, have non-optional arguments. By convention we input these in the order prescribed by the function itself. Eventually you will get the hang of this process and you will not need to specify to which argument each supplied variable or object is to be assigned for the more common functions.</p>
</div>
<div id="vectors-and-data-types" class="section level2">
<h2>Vectors and data types</h2>
<p>One of the most common data types in R is the vector. These are objects which are composed of a series of values which can be either numerics, characters, factors, or logicals. Suppose we go out and collect data on the lengths (in centimeters) of leaves for a BIOL 101 prac. We need to collect five measurements from three tree species We can store these data in <code>length.cm</code>:</p>
<pre class="r"><code>length.cm <- c(5.8, 4.8, 3.7, 5.3, 4.5, 8.3, 8.8, 9.7, 7.7, 8.1, 15.2, 16.1, 14.3, 12.2, 15.5)
length.cm</code></pre>
<pre><code>## [1] 5.8 4.8 3.7 5.3 4.5 8.3 8.8 9.7 7.7 8.1 15.2 16.1 14.3 12.2
## [15] 15.5</code></pre>
<p>We can then record the name of each tree in a vector in a similar manner:</p>
<pre class="r"><code>names.tree <- c("Spp 1", "Spp 1", "Spp 1", "Spp 1", "Spp 1", "Spp 2", "Spp 2", "Spp 2", "Spp 2", "Spp 2", "Spp 3", "Spp 3", "Spp 3", "Spp 3", "Spp 3")</code></pre>
<p>The quotation marks here are essential. They tell R that each value assigned to the vector is a character string. Without these quotations R will assume that <code>Spp 1</code>, <code>Spp 2</code>, and <code>Spp 3</code> are objects. This would throw an error because there are no objects with those names in our current R session.</p>
<p>We can get an overview of a vector. <code>length()</code> will tell us how long (how many elements) are in the vector:</p>
<pre class="r"><code>length.cm <- c(5.8, 4.8, 3.7, 5.3, 4.5, 8.3, 8.8, 9.7, 7.7, 8.1, 15.2, 16.1, 14.3, 12.2, 15.5)
names.tree <- c("Spp 1", "Spp 1", "Spp 1", "Spp 1", "Spp 1", "Spp 2", "Spp 2", "Spp 2", "Spp 2", "Spp 2", "Spp 3", "Spp 3", "Spp 3", "Spp 3", "Spp 3")
length(length.cm)</code></pre>
<pre><code>## [1] 15</code></pre>
<pre class="r"><code>length(names.tree)</code></pre>
<pre><code>## [1] 15</code></pre>
<p>Vectors must be made up of a series of elements of the same data type. To see the data type of a vector we can call <code>class()</code>:</p>
<pre class="r"><code>class(length.cm)</code></pre>
<pre><code>## [1] "numeric"</code></pre>
<pre class="r"><code>class(names.tree)</code></pre>
<pre><code>## [1] "character"</code></pre>
<p>When we get to larger data frames, <code>str()</code> will give us the structure of the object:</p>
<pre class="r"><code>str(length.cm)</code></pre>
<pre><code>## num [1:15] 5.8 4.8 3.7 5.3 4.5 8.3 8.8 9.7 7.7 8.1 ...</code></pre>
<pre class="r"><code>str(names.tree)</code></pre>
<pre><code>## chr [1:15] "Spp 1" "Spp 1" "Spp 1" "Spp 1" "Spp 1" "Spp 2" "Spp 2" ...</code></pre>
<p>Suppose we collected five more measurements from a fourth species, we could add these data to our vectors as follows:</p>
<pre class="r"><code>length.cm <- c(length.cm, 22.1, 22.5, 20.3, 25.1, 23.3)
names.tree <- c(names.tree, "Spp 4", "Spp 4", "Spp 4", "Spp 4", "Spp 4")
length.cm</code></pre>
<pre><code>## [1] 5.8 4.8 3.7 5.3 4.5 8.3 8.8 9.7 7.7 8.1 15.2 16.1 14.3 12.2
## [15] 15.5 22.1 22.5 20.3 25.1 23.3</code></pre>
<pre><code>## [1] "Spp 1" "Spp 1" "Spp 1" "Spp 1" "Spp 1" "Spp 2" "Spp 2" "Spp 2"
## [9] "Spp 2" "Spp 2" "Spp 3" "Spp 3" "Spp 3" "Spp 3" "Spp 3" "Spp 4"
## [17] "Spp 4" "Spp 4" "Spp 4" "Spp 4"</code></pre>
<p><em>Note</em> that in order to retain the original data contained in the vectors we have to ‘reassign’ the vector to itself together with the new data. If we did not do that the new data would override the original data. These are the two fundamental data types in R but there are a few others that are important:</p>
<ul>
<li><p><code>"logical"</code> which store <code>TRUE</code> and <code>FALSE</code> (boolean) type data</p></li>
<li><p><code>"integer"</code> which store whole numbers</p></li>
</ul>
<p>Besides vectors there are several other important data structures in R. These include <code>list</code>, <code>matrix</code>, <code>data.frame</code>, <code>factor</code>, and <code>array</code>.</p>
<div id="quiz-time" class="section level3">
<h3>Quiz time</h3>
<blockquote>
<ol style="list-style-type: decimal">
<li>Vectors can be of several types but what happens if we mix different types together? <details> <summary>Answer</summary> R will implicitly convert each element to the same data type. </details></li>
<li><p>Give the data types of each of these vectors:</p>
<pre class="r"><code>num_char <- c(1, 2, 3, "a")
num_logical <- c(1, 2, 3, TRUE)
char_logical <- c("a", "b", "c", TRUE)
tricky <- c(1, 2, 3, "4")</code></pre>
<p><details> <summary>Answer</summary> <code>character</code>, <code>numeric</code>, <code>character</code>, <code>character</code>. <br> R does this by trying to find the ‘lowest common denominator’ amongst all the elements without loosing any data. </details></p></li>
<li><p>You’ve probably noticed that objects of different types get converted into a single, shared type within a vector. In R, we call converting objects from one class into another class coercion. These conversions happen according to a hierarchy, whereby some types get preferentially coerced into other types. Can you draw a diagram that represents the hierarchy of how these data types are coerced? <details> <summary>Answer</summary> logical –> numeric –> character <– logical </details></p></li>
</ol>
</blockquote>
</div>
</div>
<div id="subsetting-vectors" class="section level2">
<h2>Subsetting vectors</h2>
<p>We can call a vector’s name and it will return the entire contents of the vector:</p>
<pre class="r"><code>names.tree</code></pre>
<pre><code>## [1] "Spp 1" "Spp 1" "Spp 1" "Spp 1" "Spp 1" "Spp 2" "Spp 2" "Spp 2"
## [9] "Spp 2" "Spp 2" "Spp 3" "Spp 3" "Spp 3" "Spp 3" "Spp 3" "Spp 4"
## [17] "Spp 4" "Spp 4" "Spp 4" "Spp 4"</code></pre>
<p>but suppose we only want a few selected values of the vector. We can do this by telling R exactly what we want:</p>
<pre class="r"><code>names.tree[2]</code></pre>
<pre><code>## [1] "Spp 1"</code></pre>
<pre class="r"><code>names.tree[c(2, 6, 9)]</code></pre>
<pre><code>## [1] "Spp 1" "Spp 2" "Spp 2"</code></pre>
<p>Working with individual vectors is great - but suppose we wanted to put them together in a table form. We can do that quite easily with the <code>cbind()</code> function (this stands for “column bind”). We would bind the two vectors and then tell R that this combination must be <code>as.data.frame()</code>. This converts these two vectors (initially a matrix) into an object that has columns and rows much like a spreadsheet does:</p>
<pre class="r"><code>data.prac <- as.data.frame(cbind(names.tree, length.cm))
data.prac</code></pre>
<pre><code>## names.tree length.cm
## 1 Spp 1 5.8
## 2 Spp 1 4.8
## 3 Spp 1 3.7
## 4 Spp 1 5.3
## 5 Spp 1 4.5
## 6 Spp 2 8.3
## 7 Spp 2 8.8
## 8 Spp 2 9.7
## 9 Spp 2 7.7
## 10 Spp 2 8.1
## 11 Spp 3 15.2
## 12 Spp 3 16.1
## 13 Spp 3 14.3
## 14 Spp 3 12.2
## 15 Spp 3 15.5
## 16 Spp 4 22.1
## 17 Spp 4 22.5
## 18 Spp 4 20.3
## 19 Spp 4 25.1
## 20 Spp 4 23.3</code></pre>
<p>Whilst we might not always have to do this kind of work (much of the data we will use in R will likely already be formatted in this manner when we import it into R) the principles described here provide a good introduction into the way you need to think in order to code effectively in R. That is all for this section - next we will move on to “data wrangling” with <code>dplyr</code>.</p>
</div>
</div>
</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>