forked from rstudio-education/hopr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathr-notation.html
722 lines (657 loc) · 58.3 KB
/
r-notation.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>6 R Notation | Hands-On Programming with R</title>
<meta name="description" content="This book will teach you how to program in R, with hands-on examples. I wrote it for non-programmers to provide a friendly introduction to the R language. You’ll learn how to load data, assemble and disassemble data objects, navigate R’s environment system, write your own functions, and use all of R’s programming tools. Throughout the book, you’ll use your newfound skills to solve practical data science problems.">
<meta name="generator" content="bookdown and GitBook 2.6.7">
<meta property="og:title" content="6 R Notation | Hands-On Programming with R" />
<meta property="og:type" content="book" />
<meta property="og:url" content="https://rstudio-education.github.io/hopr/" />
<meta property="og:image" content="https://rstudio-education.github.io/hopr/cover.png" />
<meta property="og:description" content="This book will teach you how to program in R, with hands-on examples. I wrote it for non-programmers to provide a friendly introduction to the R language. You’ll learn how to load data, assemble and disassemble data objects, navigate R’s environment system, write your own functions, and use all of R’s programming tools. Throughout the book, you’ll use your newfound skills to solve practical data science problems." />
<meta name="github-repo" content="rstudio-education/hopr" />
<meta name="twitter:card" content="summary" />
<meta name="twitter:title" content="6 R Notation | Hands-On Programming with R" />
<meta name="twitter:site" content="@statgarrett" />
<meta name="twitter:description" content="This book will teach you how to program in R, with hands-on examples. I wrote it for non-programmers to provide a friendly introduction to the R language. You’ll learn how to load data, assemble and disassemble data objects, navigate R’s environment system, write your own functions, and use all of R’s programming tools. Throughout the book, you’ll use your newfound skills to solve practical data science problems." />
<meta name="twitter:image" content="https://rstudio-education.github.io/hopr/cover.png" />
<meta name="author" content="Garrett Grolemund">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<link rel="prev" href="r-objects.html">
<link rel="next" href="modify.html">
<script src="libs/jquery-2.2.3/jquery.min.js"></script>
<link href="libs/gitbook-2.6.7/css/style.css" rel="stylesheet" />
<link href="libs/gitbook-2.6.7/css/plugin-table.css" rel="stylesheet" />
<link href="libs/gitbook-2.6.7/css/plugin-bookdown.css" rel="stylesheet" />
<link href="libs/gitbook-2.6.7/css/plugin-highlight.css" rel="stylesheet" />
<link href="libs/gitbook-2.6.7/css/plugin-search.css" rel="stylesheet" />
<link href="libs/gitbook-2.6.7/css/plugin-fontsettings.css" rel="stylesheet" />
<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>
<link rel="stylesheet" href="hopr.css" type="text/css" />
</head>
<body>
<div class="book without-animation with-summary font-size-2 font-family-1" data-basepath=".">
<div class="book-summary">
<nav role="navigation">
<ul class="summary">
<li><strong><a href="./">Hands-On Programming with R</a></strong></li>
<li class="divider"></li>
<li class="chapter" data-level="" data-path="index.html"><a href="index.html"><i class="fa fa-check"></i>Welcome</a></li>
<li class="chapter" data-level="" data-path="preface.html"><a href="preface.html"><i class="fa fa-check"></i>Preface</a><ul>
<li class="chapter" data-level="0.1" data-path="preface.html"><a href="preface.html#conventions-used-in-this-book"><i class="fa fa-check"></i><b>0.1</b> Conventions Used in This Book</a></li>
<li class="chapter" data-level="0.2" data-path="preface.html"><a href="preface.html#acknowledgments"><i class="fa fa-check"></i><b>0.2</b> Acknowledgments</a></li>
</ul></li>
<li class="part"><span><b>I Part 1</b></span></li>
<li class="chapter" data-level="1" data-path="project-1-weighted-dice.html"><a href="project-1-weighted-dice.html"><i class="fa fa-check"></i><b>1</b> Project 1: Weighted Dice</a></li>
<li class="chapter" data-level="2" data-path="basics.html"><a href="basics.html"><i class="fa fa-check"></i><b>2</b> The Very Basics</a><ul>
<li class="chapter" data-level="2.1" data-path="basics.html"><a href="basics.html#the-r-user-interface"><i class="fa fa-check"></i><b>2.1</b> The R User Interface</a></li>
<li class="chapter" data-level="2.2" data-path="basics.html"><a href="basics.html#objects"><i class="fa fa-check"></i><b>2.2</b> Objects</a></li>
<li class="chapter" data-level="2.3" data-path="basics.html"><a href="basics.html#functions"><i class="fa fa-check"></i><b>2.3</b> Functions</a><ul>
<li class="chapter" data-level="2.3.1" data-path="basics.html"><a href="basics.html#sample-with-replacement"><i class="fa fa-check"></i><b>2.3.1</b> Sample with Replacement</a></li>
</ul></li>
<li class="chapter" data-level="2.4" data-path="basics.html"><a href="basics.html#write-functions"><i class="fa fa-check"></i><b>2.4</b> Writing Your Own Functions</a><ul>
<li class="chapter" data-level="2.4.1" data-path="basics.html"><a href="basics.html#the-function-constructor"><i class="fa fa-check"></i><b>2.4.1</b> The Function Constructor</a></li>
</ul></li>
<li class="chapter" data-level="2.5" data-path="basics.html"><a href="basics.html#arguments"><i class="fa fa-check"></i><b>2.5</b> Arguments</a></li>
<li class="chapter" data-level="2.6" data-path="basics.html"><a href="basics.html#scripts"><i class="fa fa-check"></i><b>2.6</b> Scripts</a></li>
<li class="chapter" data-level="2.7" data-path="basics.html"><a href="basics.html#summary"><i class="fa fa-check"></i><b>2.7</b> Summary</a></li>
</ul></li>
<li class="chapter" data-level="3" data-path="packages.html"><a href="packages.html"><i class="fa fa-check"></i><b>3</b> Packages and Help Pages</a><ul>
<li class="chapter" data-level="3.1" data-path="packages.html"><a href="packages.html#packages-1"><i class="fa fa-check"></i><b>3.1</b> Packages</a><ul>
<li class="chapter" data-level="3.1.1" data-path="packages.html"><a href="packages.html#install.packages"><i class="fa fa-check"></i><b>3.1.1</b> install.packages</a></li>
<li class="chapter" data-level="3.1.2" data-path="packages.html"><a href="packages.html#library"><i class="fa fa-check"></i><b>3.1.2</b> library</a></li>
</ul></li>
<li class="chapter" data-level="3.2" data-path="packages.html"><a href="packages.html#getting-help-with-help-pages"><i class="fa fa-check"></i><b>3.2</b> Getting Help with Help Pages</a><ul>
<li class="chapter" data-level="3.2.1" data-path="packages.html"><a href="packages.html#parts-of-a-help-page"><i class="fa fa-check"></i><b>3.2.1</b> Parts of a Help Page</a></li>
<li class="chapter" data-level="3.2.2" data-path="packages.html"><a href="packages.html#getting-more-help"><i class="fa fa-check"></i><b>3.2.2</b> Getting More Help</a></li>
</ul></li>
<li class="chapter" data-level="3.3" data-path="packages.html"><a href="packages.html#summary-1"><i class="fa fa-check"></i><b>3.3</b> Summary</a></li>
<li class="chapter" data-level="3.4" data-path="packages.html"><a href="packages.html#project-1-wrap-up"><i class="fa fa-check"></i><b>3.4</b> Project 1 Wrap-up</a></li>
</ul></li>
<li class="part"><span><b>II Part 2</b></span></li>
<li class="chapter" data-level="4" data-path="project-2-playing-cards.html"><a href="project-2-playing-cards.html"><i class="fa fa-check"></i><b>4</b> Project 2: Playing Cards</a></li>
<li class="chapter" data-level="5" data-path="r-objects.html"><a href="r-objects.html"><i class="fa fa-check"></i><b>5</b> R Objects</a><ul>
<li class="chapter" data-level="5.1" data-path="r-objects.html"><a href="r-objects.html#atomic-vectors"><i class="fa fa-check"></i><b>5.1</b> Atomic Vectors</a><ul>
<li class="chapter" data-level="5.1.1" data-path="r-objects.html"><a href="r-objects.html#doubles"><i class="fa fa-check"></i><b>5.1.1</b> Doubles</a></li>
<li class="chapter" data-level="5.1.2" data-path="r-objects.html"><a href="r-objects.html#integers"><i class="fa fa-check"></i><b>5.1.2</b> Integers</a></li>
<li class="chapter" data-level="5.1.3" data-path="r-objects.html"><a href="r-objects.html#characters"><i class="fa fa-check"></i><b>5.1.3</b> Characters</a></li>
<li class="chapter" data-level="5.1.4" data-path="r-objects.html"><a href="r-objects.html#logicals"><i class="fa fa-check"></i><b>5.1.4</b> Logicals</a></li>
<li class="chapter" data-level="5.1.5" data-path="r-objects.html"><a href="r-objects.html#complex-and-raw"><i class="fa fa-check"></i><b>5.1.5</b> Complex and Raw</a></li>
</ul></li>
<li class="chapter" data-level="5.2" data-path="r-objects.html"><a href="r-objects.html#attributes"><i class="fa fa-check"></i><b>5.2</b> Attributes</a><ul>
<li class="chapter" data-level="5.2.1" data-path="r-objects.html"><a href="r-objects.html#names"><i class="fa fa-check"></i><b>5.2.1</b> Names</a></li>
<li class="chapter" data-level="5.2.2" data-path="r-objects.html"><a href="r-objects.html#dim"><i class="fa fa-check"></i><b>5.2.2</b> Dim</a></li>
</ul></li>
<li class="chapter" data-level="5.3" data-path="r-objects.html"><a href="r-objects.html#matrices"><i class="fa fa-check"></i><b>5.3</b> Matrices</a></li>
<li class="chapter" data-level="5.4" data-path="r-objects.html"><a href="r-objects.html#arrays"><i class="fa fa-check"></i><b>5.4</b> Arrays</a></li>
<li class="chapter" data-level="5.5" data-path="r-objects.html"><a href="r-objects.html#class"><i class="fa fa-check"></i><b>5.5</b> Class</a><ul>
<li class="chapter" data-level="5.5.1" data-path="r-objects.html"><a href="r-objects.html#dates-and-times"><i class="fa fa-check"></i><b>5.5.1</b> Dates and Times</a></li>
<li class="chapter" data-level="5.5.2" data-path="r-objects.html"><a href="r-objects.html#factors"><i class="fa fa-check"></i><b>5.5.2</b> Factors</a></li>
</ul></li>
<li class="chapter" data-level="5.6" data-path="r-objects.html"><a href="r-objects.html#coercion"><i class="fa fa-check"></i><b>5.6</b> Coercion</a></li>
<li class="chapter" data-level="5.7" data-path="r-objects.html"><a href="r-objects.html#lists"><i class="fa fa-check"></i><b>5.7</b> Lists</a></li>
<li class="chapter" data-level="5.8" data-path="r-objects.html"><a href="r-objects.html#data-frames"><i class="fa fa-check"></i><b>5.8</b> Data Frames</a></li>
<li class="chapter" data-level="5.9" data-path="r-objects.html"><a href="r-objects.html#loading"><i class="fa fa-check"></i><b>5.9</b> Loading Data</a></li>
<li class="chapter" data-level="5.10" data-path="r-objects.html"><a href="r-objects.html#saving-data"><i class="fa fa-check"></i><b>5.10</b> Saving Data</a></li>
<li class="chapter" data-level="5.11" data-path="r-objects.html"><a href="r-objects.html#summary-2"><i class="fa fa-check"></i><b>5.11</b> Summary</a></li>
</ul></li>
<li class="chapter" data-level="6" data-path="r-notation.html"><a href="r-notation.html"><i class="fa fa-check"></i><b>6</b> R Notation</a><ul>
<li class="chapter" data-level="6.1" data-path="r-notation.html"><a href="r-notation.html#selecting-values"><i class="fa fa-check"></i><b>6.1</b> Selecting Values</a><ul>
<li class="chapter" data-level="6.1.1" data-path="r-notation.html"><a href="r-notation.html#positive-integers"><i class="fa fa-check"></i><b>6.1.1</b> Positive Integers</a></li>
<li class="chapter" data-level="6.1.2" data-path="r-notation.html"><a href="r-notation.html#negative-integers"><i class="fa fa-check"></i><b>6.1.2</b> Negative Integers</a></li>
<li class="chapter" data-level="6.1.3" data-path="r-notation.html"><a href="r-notation.html#zero"><i class="fa fa-check"></i><b>6.1.3</b> Zero</a></li>
<li class="chapter" data-level="6.1.4" data-path="r-notation.html"><a href="r-notation.html#blank-spaces"><i class="fa fa-check"></i><b>6.1.4</b> Blank Spaces</a></li>
<li class="chapter" data-level="6.1.5" data-path="r-notation.html"><a href="r-notation.html#logic"><i class="fa fa-check"></i><b>6.1.5</b> Logical Values</a></li>
<li class="chapter" data-level="6.1.6" data-path="r-notation.html"><a href="r-notation.html#names-1"><i class="fa fa-check"></i><b>6.1.6</b> Names</a></li>
</ul></li>
<li class="chapter" data-level="6.2" data-path="r-notation.html"><a href="r-notation.html#deal-a-card"><i class="fa fa-check"></i><b>6.2</b> Deal a Card</a></li>
<li class="chapter" data-level="6.3" data-path="r-notation.html"><a href="r-notation.html#shuffle-the-deck"><i class="fa fa-check"></i><b>6.3</b> Shuffle the Deck</a></li>
<li class="chapter" data-level="6.4" data-path="r-notation.html"><a href="r-notation.html#dollar-signs-and-double-brackets"><i class="fa fa-check"></i><b>6.4</b> Dollar Signs and Double Brackets</a></li>
<li class="chapter" data-level="6.5" data-path="r-notation.html"><a href="r-notation.html#summary-3"><i class="fa fa-check"></i><b>6.5</b> Summary</a></li>
</ul></li>
<li class="chapter" data-level="7" data-path="modify.html"><a href="modify.html"><i class="fa fa-check"></i><b>7</b> Modifying Values</a><ul>
<li class="chapter" data-level="7.0.1" data-path="modify.html"><a href="modify.html#changing-values-in-place"><i class="fa fa-check"></i><b>7.0.1</b> Changing Values in Place</a></li>
<li class="chapter" data-level="7.0.2" data-path="modify.html"><a href="modify.html#logical-subsetting"><i class="fa fa-check"></i><b>7.0.2</b> Logical Subsetting</a></li>
<li class="chapter" data-level="7.0.3" data-path="modify.html"><a href="modify.html#missing"><i class="fa fa-check"></i><b>7.0.3</b> Missing Information</a></li>
<li class="chapter" data-level="7.0.4" data-path="modify.html"><a href="modify.html#summary-4"><i class="fa fa-check"></i><b>7.0.4</b> Summary</a></li>
</ul></li>
<li class="chapter" data-level="8" data-path="environments.html"><a href="environments.html"><i class="fa fa-check"></i><b>8</b> Environments</a><ul>
<li class="chapter" data-level="8.1" data-path="environments.html"><a href="environments.html#environments-1"><i class="fa fa-check"></i><b>8.1</b> Environments</a></li>
<li class="chapter" data-level="8.2" data-path="environments.html"><a href="environments.html#working-with-environments"><i class="fa fa-check"></i><b>8.2</b> Working with Environments</a><ul>
<li class="chapter" data-level="8.2.1" data-path="environments.html"><a href="environments.html#the-active-environment"><i class="fa fa-check"></i><b>8.2.1</b> The Active Environment</a></li>
</ul></li>
<li class="chapter" data-level="8.3" data-path="environments.html"><a href="environments.html#scoping-rules"><i class="fa fa-check"></i><b>8.3</b> Scoping Rules</a></li>
<li class="chapter" data-level="8.4" data-path="environments.html"><a href="environments.html#assignment"><i class="fa fa-check"></i><b>8.4</b> Assignment</a></li>
<li class="chapter" data-level="8.5" data-path="environments.html"><a href="environments.html#evaluation"><i class="fa fa-check"></i><b>8.5</b> Evaluation</a></li>
<li class="chapter" data-level="8.6" data-path="environments.html"><a href="environments.html#closures"><i class="fa fa-check"></i><b>8.6</b> Closures</a></li>
<li class="chapter" data-level="8.7" data-path="environments.html"><a href="environments.html#summary-5"><i class="fa fa-check"></i><b>8.7</b> Summary</a></li>
<li class="chapter" data-level="8.8" data-path="environments.html"><a href="environments.html#project-2-wrap-up"><i class="fa fa-check"></i><b>8.8</b> Project 2 Wrap-up</a></li>
</ul></li>
<li class="part"><span><b>III Part 3</b></span></li>
<li class="chapter" data-level="" data-path="project-3-slot-machine.html"><a href="project-3-slot-machine.html"><i class="fa fa-check"></i>Project 3: Slot Machine</a></li>
<li class="chapter" data-level="9" data-path="programs.html"><a href="programs.html"><i class="fa fa-check"></i><b>9</b> Programs</a><ul>
<li class="chapter" data-level="9.1" data-path="programs.html"><a href="programs.html#strategy"><i class="fa fa-check"></i><b>9.1</b> Strategy</a><ul>
<li class="chapter" data-level="9.1.1" data-path="programs.html"><a href="programs.html#sequential-steps"><i class="fa fa-check"></i><b>9.1.1</b> Sequential Steps</a></li>
<li class="chapter" data-level="9.1.2" data-path="programs.html"><a href="programs.html#parallel-cases"><i class="fa fa-check"></i><b>9.1.2</b> Parallel Cases</a></li>
</ul></li>
<li class="chapter" data-level="9.2" data-path="programs.html"><a href="programs.html#if-statements"><i class="fa fa-check"></i><b>9.2</b> if Statements</a></li>
<li class="chapter" data-level="9.3" data-path="programs.html"><a href="programs.html#else-statements"><i class="fa fa-check"></i><b>9.3</b> else Statements</a></li>
<li class="chapter" data-level="9.4" data-path="programs.html"><a href="programs.html#lookup-tables"><i class="fa fa-check"></i><b>9.4</b> Lookup Tables</a></li>
<li class="chapter" data-level="9.5" data-path="programs.html"><a href="programs.html#code-comments"><i class="fa fa-check"></i><b>9.5</b> Code Comments</a></li>
<li class="chapter" data-level="9.6" data-path="programs.html"><a href="programs.html#summary-6"><i class="fa fa-check"></i><b>9.6</b> Summary</a></li>
</ul></li>
<li class="chapter" data-level="10" data-path="s3.html"><a href="s3.html"><i class="fa fa-check"></i><b>10</b> S3</a><ul>
<li class="chapter" data-level="10.1" data-path="s3.html"><a href="s3.html#the-s3-system"><i class="fa fa-check"></i><b>10.1</b> The S3 System</a></li>
<li class="chapter" data-level="10.2" data-path="s3.html"><a href="s3.html#attributes-1"><i class="fa fa-check"></i><b>10.2</b> Attributes</a></li>
<li class="chapter" data-level="10.3" data-path="s3.html"><a href="s3.html#generic-functions"><i class="fa fa-check"></i><b>10.3</b> Generic Functions</a></li>
<li class="chapter" data-level="10.4" data-path="s3.html"><a href="s3.html#methods"><i class="fa fa-check"></i><b>10.4</b> Methods</a><ul>
<li class="chapter" data-level="10.4.1" data-path="s3.html"><a href="s3.html#method-dispatch"><i class="fa fa-check"></i><b>10.4.1</b> Method Dispatch</a></li>
</ul></li>
<li class="chapter" data-level="10.5" data-path="s3.html"><a href="s3.html#classes"><i class="fa fa-check"></i><b>10.5</b> Classes</a></li>
<li class="chapter" data-level="10.6" data-path="s3.html"><a href="s3.html#s3-and-debugging"><i class="fa fa-check"></i><b>10.6</b> S3 and Debugging</a></li>
<li class="chapter" data-level="10.7" data-path="s3.html"><a href="s3.html#s4-and-r5"><i class="fa fa-check"></i><b>10.7</b> S4 and R5</a></li>
<li class="chapter" data-level="10.8" data-path="s3.html"><a href="s3.html#summary-7"><i class="fa fa-check"></i><b>10.8</b> Summary</a></li>
</ul></li>
<li class="chapter" data-level="11" data-path="loops.html"><a href="loops.html"><i class="fa fa-check"></i><b>11</b> Loops</a><ul>
<li class="chapter" data-level="11.1" data-path="loops.html"><a href="loops.html#expected-values"><i class="fa fa-check"></i><b>11.1</b> Expected Values</a></li>
<li class="chapter" data-level="11.2" data-path="loops.html"><a href="loops.html#expand.grid"><i class="fa fa-check"></i><b>11.2</b> expand.grid</a></li>
<li class="chapter" data-level="11.3" data-path="loops.html"><a href="loops.html#for-loops"><i class="fa fa-check"></i><b>11.3</b> for Loops</a></li>
<li class="chapter" data-level="11.4" data-path="loops.html"><a href="loops.html#while-loops"><i class="fa fa-check"></i><b>11.4</b> while Loops</a></li>
<li class="chapter" data-level="11.5" data-path="loops.html"><a href="loops.html#repeat-loops"><i class="fa fa-check"></i><b>11.5</b> repeat Loops</a></li>
<li class="chapter" data-level="11.6" data-path="loops.html"><a href="loops.html#summary-8"><i class="fa fa-check"></i><b>11.6</b> Summary</a></li>
</ul></li>
<li class="chapter" data-level="12" data-path="speed.html"><a href="speed.html"><i class="fa fa-check"></i><b>12</b> Speed</a><ul>
<li class="chapter" data-level="12.1" data-path="speed.html"><a href="speed.html#vectorized-code"><i class="fa fa-check"></i><b>12.1</b> Vectorized Code</a></li>
<li class="chapter" data-level="12.2" data-path="speed.html"><a href="speed.html#how-to-write-vectorized-code"><i class="fa fa-check"></i><b>12.2</b> How to Write Vectorized Code</a></li>
<li class="chapter" data-level="12.3" data-path="speed.html"><a href="speed.html#how-to-write-fast-for-loops-in-r"><i class="fa fa-check"></i><b>12.3</b> How to Write Fast for Loops in R</a></li>
<li class="chapter" data-level="12.4" data-path="speed.html"><a href="speed.html#vectorized-code-in-practice"><i class="fa fa-check"></i><b>12.4</b> Vectorized Code in Practice</a><ul>
<li class="chapter" data-level="12.4.1" data-path="speed.html"><a href="speed.html#loops-versus-vectorized-code"><i class="fa fa-check"></i><b>12.4.1</b> Loops Versus Vectorized Code</a></li>
</ul></li>
<li class="chapter" data-level="12.5" data-path="speed.html"><a href="speed.html#summary-9"><i class="fa fa-check"></i><b>12.5</b> Summary</a></li>
<li class="chapter" data-level="12.6" data-path="speed.html"><a href="speed.html#project-3-wrap-up"><i class="fa fa-check"></i><b>12.6</b> Project 3 Wrap-up</a></li>
</ul></li>
<li class="appendix"><span><b>Appendix</b></span></li>
<li class="chapter" data-level="A" data-path="starting.html"><a href="starting.html"><i class="fa fa-check"></i><b>A</b> Installing R and RStudio</a><ul>
<li class="chapter" data-level="A.1" data-path="starting.html"><a href="starting.html#how-to-download-and-install-r"><i class="fa fa-check"></i><b>A.1</b> How to Download and Install R</a><ul>
<li class="chapter" data-level="A.1.1" data-path="starting.html"><a href="starting.html#windows"><i class="fa fa-check"></i><b>A.1.1</b> Windows</a></li>
<li class="chapter" data-level="A.1.2" data-path="starting.html"><a href="starting.html#mac"><i class="fa fa-check"></i><b>A.1.2</b> Mac</a></li>
<li class="chapter" data-level="A.1.3" data-path="starting.html"><a href="starting.html#linux"><i class="fa fa-check"></i><b>A.1.3</b> Linux</a></li>
</ul></li>
<li class="chapter" data-level="A.2" data-path="starting.html"><a href="starting.html#using-r"><i class="fa fa-check"></i><b>A.2</b> Using R</a></li>
<li class="chapter" data-level="A.3" data-path="starting.html"><a href="starting.html#rstudio"><i class="fa fa-check"></i><b>A.3</b> RStudio</a></li>
<li class="chapter" data-level="A.4" data-path="starting.html"><a href="starting.html#opening-r"><i class="fa fa-check"></i><b>A.4</b> Opening R</a></li>
</ul></li>
<li class="chapter" data-level="B" data-path="packages2.html"><a href="packages2.html"><i class="fa fa-check"></i><b>B</b> R Packages</a><ul>
<li class="chapter" data-level="B.1" data-path="packages2.html"><a href="packages2.html#installing-packages"><i class="fa fa-check"></i><b>B.1</b> Installing Packages</a></li>
<li class="chapter" data-level="B.2" data-path="packages2.html"><a href="packages2.html#loading-packages"><i class="fa fa-check"></i><b>B.2</b> Loading Packages</a></li>
</ul></li>
<li class="chapter" data-level="C" data-path="updating.html"><a href="updating.html"><i class="fa fa-check"></i><b>C</b> Updating R and Its Packages</a><ul>
<li class="chapter" data-level="C.1" data-path="updating.html"><a href="updating.html#r-packages"><i class="fa fa-check"></i><b>C.1</b> R Packages</a></li>
</ul></li>
<li class="chapter" data-level="D" data-path="dataio.html"><a href="dataio.html"><i class="fa fa-check"></i><b>D</b> Loading and Saving Data in R</a><ul>
<li class="chapter" data-level="D.1" data-path="dataio.html"><a href="dataio.html#data-sets-in-base-r"><i class="fa fa-check"></i><b>D.1</b> Data Sets in Base R</a></li>
<li class="chapter" data-level="D.2" data-path="dataio.html"><a href="dataio.html#working-directory"><i class="fa fa-check"></i><b>D.2</b> Working Directory</a></li>
<li class="chapter" data-level="D.3" data-path="dataio.html"><a href="dataio.html#plain-text-files"><i class="fa fa-check"></i><b>D.3</b> Plain-text Files</a><ul>
<li class="chapter" data-level="D.3.1" data-path="dataio.html"><a href="dataio.html#read.table"><i class="fa fa-check"></i><b>D.3.1</b> read.table</a></li>
<li class="chapter" data-level="D.3.2" data-path="dataio.html"><a href="dataio.html#the-read-family"><i class="fa fa-check"></i><b>D.3.2</b> The read Family</a></li>
<li class="chapter" data-level="D.3.3" data-path="dataio.html"><a href="dataio.html#read.fwf"><i class="fa fa-check"></i><b>D.3.3</b> read.fwf</a></li>
<li class="chapter" data-level="D.3.4" data-path="dataio.html"><a href="dataio.html#html-links"><i class="fa fa-check"></i><b>D.3.4</b> HTML Links</a></li>
<li class="chapter" data-level="D.3.5" data-path="dataio.html"><a href="dataio.html#saving-plain-text-files"><i class="fa fa-check"></i><b>D.3.5</b> Saving Plain-Text Files</a></li>
<li class="chapter" data-level="D.3.6" data-path="dataio.html"><a href="dataio.html#compressing-files"><i class="fa fa-check"></i><b>D.3.6</b> Compressing Files</a></li>
</ul></li>
<li class="chapter" data-level="D.4" data-path="dataio.html"><a href="dataio.html#r-files"><i class="fa fa-check"></i><b>D.4</b> R Files</a><ul>
<li class="chapter" data-level="D.4.1" data-path="dataio.html"><a href="dataio.html#saving-r-files"><i class="fa fa-check"></i><b>D.4.1</b> Saving R Files</a></li>
</ul></li>
<li class="chapter" data-level="D.5" data-path="dataio.html"><a href="dataio.html#excel-spreadsheets"><i class="fa fa-check"></i><b>D.5</b> Excel Spreadsheets</a><ul>
<li class="chapter" data-level="D.5.1" data-path="dataio.html"><a href="dataio.html#export-from-excel"><i class="fa fa-check"></i><b>D.5.1</b> Export from Excel</a></li>
<li class="chapter" data-level="D.5.2" data-path="dataio.html"><a href="dataio.html#copy-and-paste"><i class="fa fa-check"></i><b>D.5.2</b> Copy and Paste</a></li>
<li class="chapter" data-level="D.5.3" data-path="dataio.html"><a href="dataio.html#xlconnect"><i class="fa fa-check"></i><b>D.5.3</b> XLConnect</a></li>
<li class="chapter" data-level="D.5.4" data-path="dataio.html"><a href="dataio.html#reading-spreadsheets"><i class="fa fa-check"></i><b>D.5.4</b> Reading Spreadsheets</a></li>
<li class="chapter" data-level="D.5.5" data-path="dataio.html"><a href="dataio.html#writing-spreadsheets"><i class="fa fa-check"></i><b>D.5.5</b> Writing Spreadsheets</a></li>
</ul></li>
<li class="chapter" data-level="D.6" data-path="dataio.html"><a href="dataio.html#loading-files-from-other-programs"><i class="fa fa-check"></i><b>D.6</b> Loading Files from Other Programs</a><ul>
<li class="chapter" data-level="D.6.1" data-path="dataio.html"><a href="dataio.html#connecting-to-databases"><i class="fa fa-check"></i><b>D.6.1</b> Connecting to Databases</a></li>
</ul></li>
</ul></li>
<li class="chapter" data-level="E" data-path="debug.html"><a href="debug.html"><i class="fa fa-check"></i><b>E</b> Debugging R Code</a><ul>
<li class="chapter" data-level="E.1" data-path="debug.html"><a href="debug.html#traceback"><i class="fa fa-check"></i><b>E.1</b> traceback</a></li>
<li class="chapter" data-level="E.2" data-path="debug.html"><a href="debug.html#browser"><i class="fa fa-check"></i><b>E.2</b> browser</a></li>
<li class="chapter" data-level="E.3" data-path="debug.html"><a href="debug.html#break-points"><i class="fa fa-check"></i><b>E.3</b> Break Points</a></li>
<li class="chapter" data-level="E.4" data-path="debug.html"><a href="debug.html#debug-1"><i class="fa fa-check"></i><b>E.4</b> debug</a></li>
<li class="chapter" data-level="E.5" data-path="debug.html"><a href="debug.html#trace"><i class="fa fa-check"></i><b>E.5</b> trace</a></li>
<li class="chapter" data-level="E.6" data-path="debug.html"><a href="debug.html#recover"><i class="fa fa-check"></i><b>E.6</b> recover</a></li>
</ul></li>
</ul>
</nav>
</div>
<div class="book-body">
<div class="body-inner">
<div class="book-header" role="navigation">
<h1>
<i class="fa fa-circle-o-notch fa-spin"></i><a href="./">Hands-On Programming with R</a>
</h1>
</div>
<div class="page-wrapper" tabindex="-1" role="main">
<div class="page-inner">
<section class="normal" id="section-">
<div id="r-notation" class="section level1">
<h1><span class="header-section-number">6</span> R Notation</h1>
<p>Now that you have a deck of cards, you need a way to do card-like things with it. First, you’ll want to reshuffle the deck from time to time. And next, you’ll want to deal cards from the deck (one card at a time, whatever card is on top—we’re not cheaters).</p>
<p>To do these things, you’ll need to work with the individual values inside your data frame, a task essential to data science. For example, to deal a card from the top of your deck, you’ll need to write a function that selects the first row of values in your data frame, like this</p>
<pre class="sourceCode r"><code class="sourceCode r"><span class="kw">deal</span>(deck)
## face suit value
## king spades 13</code></pre>
<p>You can select values within an R object with R’s notation system.</p>
<div id="selecting-values" class="section level2">
<h2><span class="header-section-number">6.1</span> Selecting Values</h2>
<p>R has a notation system that lets you extract values from R objects. To extract a value or set of values from a data frame, write the data frame’s name followed by a pair of hard brackets:</p>
<pre class="sourceCode r"><code class="sourceCode r">deck[ , ]</code></pre>
<p>Between the brackets will go two indexes separated by a comma. The indexes tell R which values to return. R will use the first index to subset the rows of the data frame and the second index to subset the columns.</p>
<p>You have a choice when it comes to writing indexes. There are six different ways to write an index for R, and each does something slightly different. They are all very simple and quite handy, so let’s take a look at each of them. You can create indexes with:</p>
<ul>
<li>Positive integers</li>
<li>Negative integers</li>
<li>Zero</li>
<li>Blank spaces</li>
<li>Logical values</li>
<li>Names</li>
</ul>
<p>The simplest of these to use is positive integers.</p>
<div id="positive-integers" class="section level3">
<h3><span class="header-section-number">6.1.1</span> Positive Integers</h3>
<p>R treats positive integers just like <em>ij</em> notation in linear algebra: <code>deck[i,j]</code> will return the value of <code>deck</code> that is in the <em>ith</em> row and the <em>jth</em> column, Figure <a href="r-notation.html#fig:positive">6.1</a>. Notice that <em>i</em> and <em>j</em> only need to be integers in the mathematical sense. They can be saved as numerics in R</p>
<pre class="sourceCode r"><code class="sourceCode r"><span class="kw">head</span>(deck)
## face suit value
## king spades 13
## queen spades 12
## jack spades 11
## ten spades 10
## nine spades 9
## eight spades 8
deck[<span class="dv">1</span>, <span class="dv">1</span>]
## "king"</code></pre>
<p>To extract more than one value, use a vector of positive integers. For example, you can return the first row of <code>deck</code> with <code>deck[1, c(1, 2, 3)]</code> or <code>deck[1, 1:3]</code>:</p>
<pre class="sourceCode r"><code class="sourceCode r">deck[<span class="dv">1</span>, <span class="kw">c</span>(<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>)]
## face suit value
## king spades 13</code></pre>
<p>R will return the values of <code>deck</code> that are in both the first row and the first, second, and third columns. Note that R won’t actually remove these values from <code>deck</code>. R will give you a new set of values which are copies of the original values. You can then save this new set to an R object with R’s assignment operator:</p>
<pre class="sourceCode r"><code class="sourceCode r">new <-<span class="st"> </span>deck[<span class="dv">1</span>, <span class="kw">c</span>(<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>)]
new
## face suit value
## king spades 13</code></pre>
<div class="rmdtip">
<p><strong>Repetition</strong></p>
<p>If you repeat a number in your index, R will return the corresponding value(s) more than once in your “subset.” This code will return the first row of <code>deck</code> twice:</p>
<pre><code>deck[c(1, 1), c(1, 2, 3)]
## face suit value
## king spades 13
## king spades 13</code></pre>
</div>
<div class="figure"><span id="fig:positive"></span>
<img src="images/hopr_0401.png" alt="R uses the _ij_ notation system of linear algebra. The commands in this figure will return the shaded values." />
<p class="caption">
Figure 6.1: R uses the <em>ij</em> notation system of linear algebra. The commands in this figure will return the shaded values.
</p>
</div>
<p>R’s notation system is not limited to data frames. You can use the same syntax to select values in any R object, as long as you supply one index for each dimension of the object. So, for example, you can subset a vector (which has one dimension) with a single index:</p>
<pre class="sourceCode r"><code class="sourceCode r">vec <-<span class="st"> </span><span class="kw">c</span>(<span class="dv">6</span>, <span class="dv">1</span>, <span class="dv">3</span>, <span class="dv">6</span>, <span class="dv">10</span>, <span class="dv">5</span>)
vec[<span class="dv">1</span><span class="op">:</span><span class="dv">3</span>]
## 6 1 3</code></pre>
<div class="rmdtip">
<p><strong>Indexing begins at 1</strong></p>
<p>In some programming languages, indexing begins with 0. This means that 0 returns the first element of a vector, 1 returns the second element, and so on.</p>
This isn’t the case with R. Indexing in R behaves just like indexing in linear algebra. The first element is always indexed by 1. Why is R different? Maybe because it was written for mathematicians. Those of us who learned indexing from a linear algebra course wonder why computers programmers start with 0.
</div>
<div class="rmdtip">
<p><strong>drop = FALSE</strong></p>
<p>If you select two or more columns from a data frame, R will return a new data frame:</p>
<pre><code>deck[1:2, 1:2]
## face suit
## king spades
## queen spades</code></pre>
<p>However, if you select a single column, R will return a vector:</p>
<pre><code>deck[1:2, 1]
## "king" "queen"</code></pre>
<p>If you would prefer a data frame instead, you can add the optional argument <code>drop = FALSE</code> between the brackets:</p>
<pre><code>deck[1:2, 1, drop = FALSE]
## face
## king
## queen</code></pre>
This method also works for selecting a single column from a matrix or an array.
</div>
</div>
<div id="negative-integers" class="section level3">
<h3><span class="header-section-number">6.1.2</span> Negative Integers</h3>
<p>Negative integers do the exact opposite of positive integers when indexing. R will return every element <em>except</em> the elements in a negative index. For example, <code>deck[-1, 1:3]</code> will return everything <em>but</em> the first row of <code>deck</code>. <code>deck[-(2:52), 1:3]</code> will return the first row (and exclude everything else):</p>
<pre class="sourceCode r"><code class="sourceCode r">deck[<span class="op">-</span>(<span class="dv">2</span><span class="op">:</span><span class="dv">52</span>), <span class="dv">1</span><span class="op">:</span><span class="dv">3</span>]
## face suit value
## king spades 13</code></pre>
<p>Negative integers are a more efficient way to subset than positive integers if you want to include the majority of a data frame’s rows or columns.</p>
<p>R will return an error if you try to pair a negative integer with a positive integer in the <em>same</em> index:</p>
<pre class="sourceCode r"><code class="sourceCode r">deck[<span class="kw">c</span>(<span class="op">-</span><span class="dv">1</span>, <span class="dv">1</span>), <span class="dv">1</span>]
## Error in xj[i] : only 0's may be mixed with negative subscripts</code></pre>
<p>However, you can use both negative and positive integers to subset an object if you use them in <em>different</em> indexes (e.g., if you use one in the rows index and one in the columns index, like <code>deck[-1, 1]</code>).</p>
</div>
<div id="zero" class="section level3">
<h3><span class="header-section-number">6.1.3</span> Zero</h3>
<p>What would happen if you used zero as an index? Zero is neither a positive integer nor a negative integer, but R will still use it to do a type of subsetting. R will return nothing from a dimension when you use zero as an index. This creates an empty object:</p>
<pre class="sourceCode r"><code class="sourceCode r">deck[<span class="dv">0</span>, <span class="dv">0</span>]
## data frame with 0 columns and 0 rows</code></pre>
<p>To be honest, indexing with zero is not very helpful.</p>
</div>
<div id="blank-spaces" class="section level3">
<h3><span class="header-section-number">6.1.4</span> Blank Spaces</h3>
<p>You can use a blank space to tell R to extract <em>every</em> value in a dimension. This lets you subset an object on one dimension but not the others, which is useful for extracting entire rows or columns from a data frame:</p>
<pre class="sourceCode r"><code class="sourceCode r">deck[<span class="dv">1</span>, ]
## face suit value
## king spades 13</code></pre>
</div>
<div id="logic" class="section level3">
<h3><span class="header-section-number">6.1.5</span> Logical Values</h3>
<p>If you supply a vector of <code>TRUE</code>s and <code>FALSE</code>s as your index, R will match each <code>TRUE</code> and <code>FALSE</code> to a row in your data frame (or a column depending on where you place the index). R will then return each row that corresponds to a <code>TRUE</code>, Figure <a href="r-notation.html#fig:logicals">6.2</a>.</p>
<p>It may help to imagine R reading through the data frame and asking, "Should I return the _i_th row of the data structure?" and then consulting the _i_th value of the index for its answer. For this system to work, your vector must be as long as the dimension you are trying to subset:</p>
<pre class="sourceCode r"><code class="sourceCode r">deck[<span class="dv">1</span>, <span class="kw">c</span>(<span class="ot">TRUE</span>, <span class="ot">TRUE</span>, <span class="ot">FALSE</span>)]
## face suit
## king spades
rows <-<span class="st"> </span><span class="kw">c</span>(<span class="ot">TRUE</span>, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F,
F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F,
F, F, F, F, F, F, F, F, F, F, F, F, F, F)
deck[rows, ]
## face suit value
## king spades 13</code></pre>
<div class="figure"><span id="fig:logicals"></span>
<img src="images/hopr_0402.png" alt="You can use vectors of TRUEs and FALSEs to tell R exactly which values you want to extract and which you do not. The command would return just the numbers 1, 6, and 5." />
<p class="caption">
Figure 6.2: You can use vectors of TRUEs and FALSEs to tell R exactly which values you want to extract and which you do not. The command would return just the numbers 1, 6, and 5.
</p>
</div>
<p>This system may seem odd—who wants to type so many <code>TRUE</code>s and <code>FALSE</code>s?—but it will become very powerful in <a href="modify.html#modify">Modifying Values</a>.</p>
</div>
<div id="names-1" class="section level3">
<h3><span class="header-section-number">6.1.6</span> Names</h3>
<p>Finally, you can ask for the elements you want by name—if your object has names (see <a href="r-objects.html#names">Names</a>). This is a common way to extract the columns of a data frame, since columns almost always have names:</p>
<pre class="sourceCode r"><code class="sourceCode r">deck[<span class="dv">1</span>, <span class="kw">c</span>(<span class="st">"face"</span>, <span class="st">"suit"</span>, <span class="st">"value"</span>)]
## face suit value
## king spades 13
<span class="co"># the entire value column</span>
deck[ , <span class="st">"value"</span>]
## 13 12 11 10 9 8 7 6 5 4 3 2 1 13 12 11 10 9 8
## 7 6 5 4 3 2 1 13 12 11 10 9 8 7 6 5 4 3 2
## 1 13 12 11 10 9 8 7 6 5 4 3 2 1</code></pre>
</div>
</div>
<div id="deal-a-card" class="section level2">
<h2><span class="header-section-number">6.2</span> Deal a Card</h2>
<p>Now that you know the basics of R’s notation system, let’s put it to use.</p>
<div class="exercise">
<span id="exr:unnamed-chunk-28" class="exercise"><strong>Exercise 6.1 (Deal a Card) </strong></span>Complete the following code to make a function that returns the first row of a data frame:
</div>
<pre class="sourceCode r"><code class="sourceCode r">deal <-<span class="st"> </span><span class="cf">function</span>(cards) {
<span class="co"># ?</span>
}</code></pre>
<div class="solution">
<span class="solution"><em>Solution. </em></span> You can use any of the systems that return the first row of your data frame to write a <code>deal</code> function. I’ll use positive integers and blanks because I think they are easy to understand:
</div>
<pre class="sourceCode r"><code class="sourceCode r">deal <-<span class="st"> </span><span class="cf">function</span>(cards) {
cards[<span class="dv">1</span>, ]
}</code></pre>
<p>The function does exactly what you want: it deals the top card from your data set. However, the function becomes less impressive if you run <code>deal</code> over and over again:</p>
<pre class="sourceCode r"><code class="sourceCode r"><span class="kw">deal</span>(deck)
## face suit value
## king spades 13
<span class="kw">deal</span>(deck)
## face suit value
## king spades 13
<span class="kw">deal</span>(deck)
## face suit value
## king spades 13</code></pre>
<p><code>deal</code> always returns the king of spades because <code>deck</code> doesn’t know that we’ve dealt the card away. Hence, the king of spades stays where it is, at the top of the deck ready to be dealt again. This is a difficult problem to solve, and we will <em>deal</em> with it in <a href="environments.html#environments-1">Environments</a>. In the meantime, you can fix the problem by shuffling your deck after every deal. Then a new card will always be at the top.</p>
<p>Shuffling is a temporary compromise: the probabilities at play in your deck will not match the probabilities that occur when you play a game with a single deck of cards. For example, there will still be a probability that the king of spades appears twice in a row. However, things are not as bad as they may seem. Most casinos use five or six decks at a time in card games to prevent card counting. The probabilities that you would encounter in those situations are very close to the ones we will create here.</p>
</div>
<div id="shuffle-the-deck" class="section level2">
<h2><span class="header-section-number">6.3</span> Shuffle the Deck</h2>
<p>When you shuffle a real deck of cards, you randomly rearrange the order of the cards. In your virtual deck, each card is a row in a data frame. To shuffle the deck, you need to randomly reorder the rows in the data frame. Can this be done? You bet! And you already know everything you need to do it.</p>
<p>This may sound silly, but start by extracting every row in your data frame:</p>
<pre class="sourceCode r"><code class="sourceCode r">deck2 <-<span class="st"> </span>deck[<span class="dv">1</span><span class="op">:</span><span class="dv">52</span>, ]
<span class="kw">head</span>(deck2)
## face suit value
## king spades 13
## queen spades 12
## jack spades 11
## ten spades 10
## nine spades 9
## eight spades 8</code></pre>
<p>What do you get? A new data frame whose order hasn’t changed at all. What if you asked R to extract the rows in a different order? For example, you could ask for row 2, <em>then</em> row 1, and then the rest of the cards:</p>
<pre class="sourceCode r"><code class="sourceCode r">deck3 <-<span class="st"> </span>deck[<span class="kw">c</span>(<span class="dv">2</span>, <span class="dv">1</span>, <span class="dv">3</span><span class="op">:</span><span class="dv">52</span>), ]
<span class="kw">head</span>(deck3)
## face suit value
## queen spades 12
## king spades 13
## jack spades 11
## ten spades 10
## nine spades 9
## eight spades 8</code></pre>
<p>R complies. You’ll get all the rows back, and they’ll come in the order you ask for them. If you want the rows to come in a random order, then you need to sort the integers from 1 to 52 into a random order and use the results as a row index. How could you generate such a random collection of integers? With our friendly neighborhood <code>sample</code> function:</p>
<pre class="sourceCode r"><code class="sourceCode r">random <-<span class="st"> </span><span class="kw">sample</span>(<span class="dv">1</span><span class="op">:</span><span class="dv">52</span>, <span class="dt">size =</span> <span class="dv">52</span>)
random
## 35 28 39 9 18 29 26 45 47 48 23 22 21 16 32 38 1 15 20
## 11 2 4 14 49 34 25 8 6 10 41 46 17 33 5 7 44 3 27
## 50 12 51 40 52 24 19 13 42 37 43 36 31 30
deck4 <-<span class="st"> </span>deck[random, ]
<span class="kw">head</span>(deck4)
## face suit value
## five diamonds 5
## queen diamonds 12
## ace diamonds 1
## five spades 5
## nine clubs 9
## jack diamonds 11</code></pre>
<p>Now the new set is truly shuffled. You’ll be finished once you wrap these steps into a function.</p>
<div class="exercise">
<span id="exr:unnamed-chunk-30" class="exercise"><strong>Exercise 6.2 (Shuffle a Deck) </strong></span>Use the preceding ideas to write a <code>shuffle</code> function. <code>shuffle</code> should take a data frame and return a shuffled copy of the data frame.
</div>
<div class="solution">
<span class="solution"><em>Solution. </em></span> Your <code>shuffle</code> function will look like the one that follows:
</div>
<pre class="sourceCode r"><code class="sourceCode r">shuffle <-<span class="st"> </span><span class="cf">function</span>(cards) {
random <-<span class="st"> </span><span class="kw">sample</span>(<span class="dv">1</span><span class="op">:</span><span class="dv">52</span>, <span class="dt">size =</span> <span class="dv">52</span>)
cards[random, ]
}</code></pre>
<p>Nice work! Now you can shuffle your cards between each deal:</p>
<pre class="sourceCode r"><code class="sourceCode r"><span class="kw">deal</span>(deck)
## face suit value
## king spades 13
deck2 <-<span class="st"> </span><span class="kw">shuffle</span>(deck)
<span class="kw">deal</span>(deck2)
## face suit value
## jack clubs 11</code></pre>
</div>
<div id="dollar-signs-and-double-brackets" class="section level2">
<h2><span class="header-section-number">6.4</span> Dollar Signs and Double Brackets</h2>
<p>Two types of object in R obey an optional second system of notation. You can extract values from data frames and lists with the <code>$</code> syntax. You will encounter the <code>$</code> syntax again and again as an R programmer, so let’s examine how it works.</p>
<p>To select a column from a data frame, write the data frame’s name and the column name separated by a <code>$</code>. Notice that no quotes should go around the column name:</p>
<pre class="sourceCode r"><code class="sourceCode r">deck<span class="op">$</span>value
## 13 12 11 10 9 8 7 6 5 4 3 2 1 13 12 11 10 9 8 7
## 6 5 4 3 2 1 13 12 11 10 9 8 7 6 5 4 3 2 1 13
## 12 11 10 9 8 7 6 5 4 3 2 1</code></pre>
<p>R will return all of the values in the column as a vector. This <code>$</code> notation is incredibly useful because you will often store the variables of your data sets as columns in a data frame. From time to time, you’ll want to run a function like <code>mean</code> or <code>median</code> on the values in a variable. In R, these functions expect a vector of values as input, and <code>deck$value</code> delivers your data in just the right format:</p>
<pre class="sourceCode r"><code class="sourceCode r"><span class="kw">mean</span>(deck<span class="op">$</span>value)
## 7
<span class="kw">median</span>(deck<span class="op">$</span>value)
## 7</code></pre>
<p>You can use the same <code>$</code> notation with the elements of a list, if they have names. This notation has an advantage with lists, too. If you subset a list in the usual way, R will return a <em>new</em> list that has the elements you requested. This is true even if you only request a single element.</p>
<p>To see this, make a list:</p>
<pre class="sourceCode r"><code class="sourceCode r">lst <-<span class="st"> </span><span class="kw">list</span>(<span class="dt">numbers =</span> <span class="kw">c</span>(<span class="dv">1</span>, <span class="dv">2</span>), <span class="dt">logical =</span> <span class="ot">TRUE</span>, <span class="dt">strings =</span> <span class="kw">c</span>(<span class="st">"a"</span>, <span class="st">"b"</span>, <span class="st">"c"</span>))
lst
## $numbers
## [1] 1 2
## $logical
## [1] TRUE
## $strings
## [1] "a" "b" "c"</code></pre>
<p>And then subset it:</p>
<pre class="sourceCode r"><code class="sourceCode r">lst[<span class="dv">1</span>]
## $numbers
## [1] 1 2</code></pre>
<p>The result is a smaller <em>list</em> with one element. That element is the vector <code>c(1, 2)</code>. This can be annoying because many R functions do not work with lists. For example, <code>sum(lst[1])</code> will return an error. It would be horrible if once you stored a vector in a list, you could only ever get it back as a list:</p>
<pre class="sourceCode r"><code class="sourceCode r"><span class="kw">sum</span>(lst[<span class="dv">1</span>])
## Error in sum(lst[1]) : invalid 'type' (list) of argument</code></pre>
<p>When you use the <code>$</code> notation, R will return the selected values as they are, with no list structure around them:</p>
<pre class="sourceCode r"><code class="sourceCode r">lst<span class="op">$</span>numbers
## 1 2</code></pre>
<p>You can then immediately feed the results to a function:</p>
<pre class="sourceCode r"><code class="sourceCode r"><span class="kw">sum</span>(lst<span class="op">$</span>numbers)
## 3</code></pre>
<p>If the elements in your list do not have names (or you do not wish to use the names), you can use two brackets, instead of one, to subset the list. This notation will do the same thing as the <code>$</code> notation:</p>
<pre class="sourceCode r"><code class="sourceCode r">lst[[<span class="dv">1</span>]]
## 1 2</code></pre>
<p>In other words, if you subset a list with single-bracket notation, R will return a smaller list. If you subset a list with double-bracket notation, R will return just the values that were inside an element of the list. You can combine this feature with any of R’s indexing methods:</p>
<pre class="sourceCode r"><code class="sourceCode r">lst[<span class="st">"numbers"</span>]
## $numbers
## [1] 1 2
lst[[<span class="st">"numbers"</span>]]
## 1 2</code></pre>
<p>This difference is subtle but important. In the R community, there is a popular, and helpful, way to think about it, Figure <a href="r-notation.html#fig:trains">6.3</a>. Imagine that each list is a train and each element is a train car. When you use single brackets, R selects individual train cars and returns them as a new train. Each car keeps its contents, but those contents are still inside a train car (i.e., a list). When you use double brackets, R actually unloads the car and gives you back the contents.</p>
<div class="figure"><span id="fig:trains"></span>
<img src="images/hopr_0403.png" alt="It can be helpful to think of your list as a train. Use single brackets to select train cars, double brackets to select the contents inside of a car." />
<p class="caption">
Figure 6.3: It can be helpful to think of your list as a train. Use single brackets to select train cars, double brackets to select the contents inside of a car.
</p>
</div>
<div class="rmdimportant">
<p><strong>Never attach</strong></p>
<p>In R’s early days, it became popular to use <code>attach()</code> on a data set once you had it loaded. Don’t do this! <code>attach</code> recreates a computing environment similar to those used in other statistics applications like Stata and SPSS, which crossover users liked. However, R is not Stata or SPSS. R is optimized to use the R computing environment, and running <code>attach()</code> can cause confusion with some R functions.</p>
What does <code>attach()</code> do? On the surface, <code>attach</code> saves you typing. If you attach the <code>deck</code> data set, you can refer to each of its variables by name; instead of typing <code>deck$face</code>, you can just type <code>face</code>. But typing isn’t bad. It gives you a chance to be explicit, and in computer programming, explicit is good. Attaching a data set creates the possibility that R will confuse two variable names. If this occurs within a function, you’re likely to get unusable results and an unhelpful error message to explain what happened.
</div>
<p>Now that you are an expert at retrieving values stored in R, let’s summarize what you’ve accomplished.</p>
</div>
<div id="summary-3" class="section level2">
<h2><span class="header-section-number">6.5</span> Summary</h2>
<p>You have learned how to access values that have been stored in R. You can retrieve a copy of values that live inside a data frame and use the copies for new computations.</p>
<p>In fact, you can use R’s notation system to access values in any R object. To use it, write the name of an object followed by brackets and indexes. If your object is one-dimensional, like a vector, you only need to supply one index. If it is two-dimensional, like a data frame, you need to supply two indexes separated by a comma. And, if it is <em>n</em>-dimensional, you need to supply <em>n</em> indexes, each separated by a comma.</p>
<p>In <a href="modify.html#modify">Modifying Values</a>, you’ll take this system a step further and learn how to change the actual values that are stored inside your data frame. This is all adding up to something special: complete control of your data. You can now store your data in your computer, retrieve individual values at will, and use your computer to perform correct calculations with those values.</p>
<p>Does this sound basic? It may be, but it is also powerful and essential for efficient data science. You no longer need to memorize everything in your head, nor worry about doing mental arithmetic wrong. This low-level control over your data is also a prerequisite for more efficient R programs, the subject of <a href="project-3-slot-machine.html#project-3-slot-machine">Project 3: Slot Machine</a>.</p>
</div>
</div>
</section>
</div>
</div>
</div>
<a href="r-objects.html" class="navigation navigation-prev " aria-label="Previous page"><i class="fa fa-angle-left"></i></a>
<a href="modify.html" class="navigation navigation-next " aria-label="Next page"><i class="fa fa-angle-right"></i></a>
</div>
</div>
<script src="libs/gitbook-2.6.7/js/app.min.js"></script>
<script src="libs/gitbook-2.6.7/js/lunr.js"></script>
<script src="libs/gitbook-2.6.7/js/plugin-search.js"></script>
<script src="libs/gitbook-2.6.7/js/plugin-sharing.js"></script>
<script src="libs/gitbook-2.6.7/js/plugin-fontsettings.js"></script>
<script src="libs/gitbook-2.6.7/js/plugin-bookdown.js"></script>
<script src="libs/gitbook-2.6.7/js/jquery.highlight.js"></script>
<script>
gitbook.require(["gitbook"], function(gitbook) {
gitbook.start({
"sharing": false,
"fontsettings": {
"theme": "white",
"family": "sans",
"size": 2
},
"edit": {
"link": "https://github.com/rstudio-education/hopr/edit/master/notation.rmd",
"text": "Edit"
},
"history": {
"link": null,
"text": null
},
"download": null,
"toc": {
"collapse": "section"
}
});
});
</script>
<!-- dynamically load mathjax for compatibility with self-contained -->
<script>
(function () {
var script = document.createElement("script");
script.type = "text/javascript";
var src = "true";
if (src === "" || src === "true") src = "https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-MML-AM_CHTML";
if (location.protocol !== "file:" && /^https?:/.test(src))
src = src.replace(/^https?:/, '');
script.src = src;
document.getElementsByTagName("head")[0].appendChild(script);
})();
</script>
</body>
</html>