-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnotes.Rmd
335 lines (237 loc) · 5.12 KB
/
notes.Rmd
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
---
title: "Stat 33A - Lecture Notes 11"
date: Nov 1, 2020
output: pdf_document
---
Printing Output
===============
The `cat` function prints a message to the console:
```{r}
cat("Hello")
cat(4)
cat("Hello", "Nick")
```
Strings lose their quotes and escape sequences are converted.
The `cat` function always returns `NULL`:
```{r}
x = cat("Hello")
x
```
The `print` function prints R's representation of an object to the console:
```{r}
print(5)
print(c(5, 6))
x = c(5, 6)
print(x)
print("Hello")
```
Strings keep their quotes and escape sequences are not converted.
The `print` function returns the object being printed:
```{r}
y = print(5)
y
```
The `show` function is similar to `print`, but always returns `NULL`.
A later lecture might cover why both `print` and `show` are necessary.
For most output, `print` is the wrong function to use!
Formatting Output
-----------------
_Escape sequences_ allow you to write characters that aren't on your keyboard
in strings.
Escape sequences always begin with a backslash.
See `?Quotes` for a complete list.
For example, `\n` is a newline:
```{r}
x = "Hello\nNick"
cat(x)
print(x)
```
The `paste` function combines strings:
```{r}
y = paste("Hello", "Nick")
y
```
The `sprintf` function can substitute values into strings.
Substitutions are marked with `%` followed by a character:
```{r}
sprintf("My age is %i, and my name is %s", 32, "Nick")
```
For-loops
=========
A for-loop runs a block of code once for each element of a vector or list:
```{r}
x = c("Hi", "Hello", "Hope you had a nice day!")
for (msg in x) {
cat(msg, "\n")
}
for (i in 1:5) {
cat("This iteration is ", i, "\n")
}
```
Curly braces `{ }` are only required if you have multiple lines of code.
You have to write code to save the results from the loop.
In other words, create a variable where you can save results.
For example:
```{r}
# Add up the cubes of the numbers
numbers = c(-4, 10, -3, 6)
total = 0
for (number in numbers) {
total = total + number^3
}
numbers
```
Use for-loops when some (or all) of the iterations depend on results from other
iterations.
If the iterations are not dependent, use one of:
1. Vectorization (because it's faster)
2. Apply functions (because they're idiomatic)
In some cases, you can use vectorization even when the iterations are
dependent. For example:
```{r}
sum(numbers^3)
```
As another example, let's use a loop to compute Fibonacci numbers.
Each Fibonacci number is the sum of the previous two. The first few Fibonacci
numbers are:
```
1 1 2 3 5 8 13
```
We can use a loop to compute the first `n` Fibonacci numbers:
```{r}
n = 10
fib = c(1, 1, numeric(n - 2))
for (i in 3:n) {
fib[i] = fib[i - 1] + fib[i - 2]
}
fib
```
If you want to reuse this code, you could make it a function:
```{r}
fibonacci = function(n = 10) {
fib = c(1, 1, numeric(n - 2))
for (i in 3:n) {
fib[i] = fib[i - 1] + fib[i - 2]
}
fib
}
fibonacci(30)
```
Break & Next
------------
Use `break` to exit a loop early:
```{r}
my_messages = list("Hi", "Hello", 5, "Goodbye")
for (msg in my_messages) {
if (is.character(msg)) {
cat(msg, "\n")
} else {
break
}
}
```
Use `next` to skip to the next iteration early:
```{r}
for (msg in my_messages) {
if (is.character(msg)) {
cat(msg, "\n")
} else {
next
}
}
```
Loop Indices
============
If you need indices, using `1:n` can cause bugs:
```{r}
n = 0
for (i in 1:n) {
message(i)
}
```
Use `seq_len(n)` instead:
```{r}
n = 0
for (i in seq_len(n)) {
message(i)
}
```
Similarly, using `1:length(x)` can cause bugs:
```{r}
#x = c(-3, 5, 7)
x = c()
for (i in 1:length(x)) {
message("The element is ", x[i])
}
```
Use `seq_along(x)` instead:
```{r}
# x = c(-3, 5, 7)
x = c()
for (i in seq_along(x)) {
message("The element is ", x[i])
}
```
More generally, use `seq()` to produce sequences of indices.
Preallocation
=============
_Preallocation_ means allocating memory for results before a computation.
These functions allocate vectors:
* `character()`
* `complex()`
* `numeric()`
* `logical()`
* `vector()`
* `rep()`
Examples:
```{r}
character(3)
complex(10)
numeric(4)
logical(3)
vector("logical", 6)
vector("list", 3)
```
Preallocation is especially important for loops:
```{r}
# BAD, NO PREALLOCATION:
x = c()
for (i in 1:1e5) {
x = c(x, i * 2)
}
x
# GOOD:
n = 1e5
x = numeric(n)
for (i in seq_len(n)) {
x[i] = i * 2
}
```
Loops Example
=============
Let's simulate a two-dimensional discrete random walk.
In a random walk, at each time step the walker randomly moves 1 unit along the
x-coordinates or the y-coordinates.
The algorithm is:
1. Flip a coin to determine whether walker moves in x or y.
2. Flip a coin to determine whether walker moves `-1` or `+1`.
3. Update the walker's position.
4. Repeat 1-3 for the desired number of steps.
We can do this with a for-loop:
```{r}
# Take n steps in a random walk.
n = 10
x = numeric(n + 1)
y = numeric(n + 1)
xy = sample(c(0, 1), n, replace = TRUE)
move = sample(c(-1, 1), n, replace = TRUE)
for (i in seq_len(n)) {
if (xy[i] == 0) { # x
x[i + 1] = x[i] + move[i]
y[i + 1] = y[i]
} else { # y
x[i + 1] = x[i]
y[i + 1] = y[i] + move[i]
}
}
```