Table of Contents
Foreword vii
Preface ix
Part I Project 1: Weighted Dice
1 The Very Basics 3
The R User Interface 3
Objects 7
Functions 12
Sample with Replacement 14
Writing Your Own Functions 16
The Function Constructor 17
Arguments 18
Scripts 20
Summary 22
2 Packages and Help Pages 23
Packages 23
install, packages 24
library 24
Getting Help with Help Pages 29
Parts of a Help Page 30
Getting More Help 33
Summary 33
Project 1 Wrap-up 34
Part II Project 2: Playing Cards
3 R Objects 37
Atomic Vectors 38
Doubles 39
Integers 40
Characters 41
Logicals 42
Complex and Raw 42
Attributes 43
Names 44
Dim 45
Matrices 46
Arrays 46
Class 47
Dates and Times 48
Factors 49
Coercion 51
Lists 53
Data Frames 55
Loading Data 57
Saving Data 61
Summary 61
4 R Notation 65
Selecting Values 65
Positive Integers 66
Negative Integers 68
Zero 69
Blank Spaces 69
Logical Values 69
Names 70
Deal a Card 70
Shuffle the Deck 71
Dollar Signs and Double Brackets 73
Summary 76
5 Modifying Values 77
Changing Values in Place 77
Logical Subsetting 80
Logical Tests 80
Boolean Operators 85
Missing Information 89
na-rm 90
is.na 90
Summary 91
6 Environments 93
Environments 93
Working with Environments 95
The Active Environment 97
Scoping Rules 98
Assignment 99
Evaluation 99
Closures 107
Summary 112
Project 2 Wrap-up 112
Part III Project 3: Slot Machine
7 Programs 115
Strategy 118
Sequential Steps 118
Parallel Cases 119
If Statements 120
else Statements 123
Lookup Tables 130
Code Comments 136
Summary 137
8 S3 139
The S3 System 139
Attributes 140
Generic Functions 145
Methods 146
Method Dispatch 148
Classes 151
S3 and Debugging 152
S4 and R5 152
Summary 152
9 Loops 155
Expected Values 155
expand.grid 157
for Loops 163
while Loops 168
repeat Loops 169
Summary 169
10 Speed 171
Vectorized Code 171
How to Write Vectorized Code 173
How to Write Fast for Loops in R 178
Vectorized Code in Practice 179
Loops Versus Vectorized Code 183
Summary 183
Project 3 Wrap-up 184
A Installing R and RStudio 187
B R Packages 191
C Updating Rand Its Packages 195
D Loading and Saving Data in R 197
E Debugging R Code 211
Index 221