-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathday4.Rmd
More file actions
407 lines (315 loc) · 11.2 KB
/
day4.Rmd
File metadata and controls
407 lines (315 loc) · 11.2 KB
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
---
title: "Intro to R 2026 day 4"
author: "Matt Cannon"
date: '2026-04-23'
output:
html_document:
code_folding: hide
toc: true
toc_depth: 2
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
Load libraries
```{r}
library(tidyverse)
```
# Day 4
## General stuff
### What is a loop?
- A way to do something over and over again
- "While I can, do push ups"
- Sometimes it's iterating over a group of things
- "For each of my shoes, tie the laces"
- Sometimes it's just doing something until a condition is met
- "If I'm hungry, keep eating ice cream"
- Can also be instructions to do things conditionally
- "If I have ice cream, eat ice cream"
- Loops are bounded by curly braces { } so you know where they start and end
### Why use a loop?
- Avoid copying and pasting code, which is error prone and time consuming
- Easier to edit afterwards if you want to change something
- Sometimes you have to do a loop
- Impractical to write the same code 10,000 times
- You don't know how many times you need to do something
```{r dont_do_this}
plot(1)
plot(2)
plot(2)
plot(3)
plot(4)
plot(5)
plot(6)
```
## Functions for today's activity
### Lists
- A list is like a vector (1 dimensional)
- Each element can be a different data type
- Each element can have a name
- To make a list, put your stuff inside a `list()` function
- To access elements of a list
- Use `$` and the name of the part if it has a name
- Use `[[ ]]` and the index (number) of the part if it doesn't have a name
- **Difference between `[]` and `[[]]`**
- `[[]]` returns an element of the list
- `[]` returns a shorter portion of the list
```{r}
bunch_o_stuff <-
list(
first = 1,
some_data = mtcars,
small_matrix = matrix(c(1, 2, 1, 2), nrow = 2),
dogs = c("fido", "toby")
)
bunch_o_stuff$first
bunch_o_stuff$small_matrix
names(bunch_o_stuff)
# What is the difference between this:
bunch_o_stuff[[1]]
# And this?
bunch_o_stuff[1]
bunch_o_stuff[3:4]
```
### if () {}
- "if" loops are used to perform some action if a condition is TRUE
- The condition is inside the parentheses
- This needs to evaluate down to TRUE or FALSE
- The code to execute is inside the curly braces
- If the condition is FALSE, nothing happens
if ( test condition ) {
do this stuff if test condition == TRUE
}
```{r}
bobs_age <- 85
bobs_age > 80
if (bobs_age > 80) {
print("Bob is probably losing hair.")
}
```
#### When to use an if () loop?
- If you need to chose when to perform some action based on some condition
- The action will not always be performed
if (the day starts with "F") {
go to the pub
}
if (length(Cells(single_cell_data)) > 1000) {
DimPlot(single_cell_data)
}
### if/else
- You can give alternatives to perform if the condition is FALSE
- "else" and "else if" () will give alternative conditions to consider
- "else if()" will take a second condition to check for
- **The conditions are considered in order**
- The second condition is only checked if the first is FALSE
if (I have my lunchbox) {
eat my lunch
} else if (I have money) {
buy lunch
} else if (Yogesh brought lunch) {
steal his lunch
} else {
go hungry
}
```{r}
darrins_age <- 15
darrins_age > 80
if (darrins_age > 80) {
print("Darrin is probably losing hair.")
} else {
print("Darrin has a full head of luscious hair.")
}
## Can test multiple conditions with else if ()
if (darrins_age > 80) {
print("Darrin is probably losing hair.")
print("other stuff")
} else if (darrins_age > 50) {
print("Darrin might be losing some hair.")
} else {
print("Darrin has lots of hair.")
}
```
### while () {}
- While the condition is TRUE, do the stuff inside the curly braces
- Use this when you don't know how many times you need to do something
- In the example with ice cream, if I specified how many bites to take, I may guess the wrong number
while (I have ice cream) {
eat ice cream
}
```{r}
bettys_age <- 1
while (bettys_age < 100) {
bettys_age <- bettys_age + 1
print(paste("Betty ages by a year and is now", bettys_age))
Sys.sleep(0.3) # This is just here so you can watch the loop happen slowly
}
print("Betty died. :'-(")
rand_num <- rnorm(1, sd = 0.5)
rand_num
tries <- 1
while (rand_num < 0.999) {
rand_num <- rnorm(1, sd = 0.5)
tries <- tries + 1
print(
paste(
rand_num,
"I tried to find a number greater than 0.999", tries, "times!"
)
)
Sys.sleep(0.1)
}
```
#### Example of an infinite loop
- An infinite loop occurs when the tested condition can never evaluate to FALSE
- This will keep going until you either stop it or the heat death of the universe
while (I'm not a billionaire) {
Give away all my money
}
```{r eval=FALSE}
bettys_age <- 1
while (bettys_age > 0) {
bettys_age <- bettys_age + 1
if (bettys_age > 1000) {
print("Holy moly!")
}
print(paste("Betty is a vampire and can never die. She is now", bettys_age))
}
```
### for () {}
- A for loop is used to iterate over a group of things
- The group of things is defined in the parentheses
- The code to execute is inside the curly braces
- You define a variable name in the parentheses that you will use in the loop
- The variable name will be the current item in the group of things
- Every iteration of the for loop will use the next item in your group
- Use a for loop when you're doing something to each item in a group of things
for (my_new_variable_name in "list/vector of things") {
my_new_variable_name now holds one of the things in the list/vector
I can now do stuff using this iteration of my_new_variable_name
}
for (this_kid in my_kids) {
feed(this_kid)
}
```{r}
list_of_friends <- list("Bob", "Jack", "Jill")
for (friend in list_of_friends) {
print(paste("I gave", friend, "a present."))
}
print(friend)
for (i in 1:10) {
print(paste("I have", i, "ice cream cones."))
}
```
### as.character(), etc…
- Data come in defined types in R
- numeric is numbers with decimals 3.14
- integer is whole numbers 3
- character is text "hello"
- logical is TRUE or FALSE TRUE
- Date is a date "1983-02-08"
- factor is a categorical variable "red", "blue", "green"
- Similar to characters, but treated like categories
- Sometimes you need to convert data from one type to another
- If you have one thing and you want it to be something else, use as.the_thing_I_want_here()
```{r}
as.character(1)
as.numeric("1")
as.logical(c(1, 0, 2, -1337)) # zero is FALSE, everything ele is TRUE
as.integer(1.)
as.Date("1983-02-08")
```
#### Beware of coercion!
- R will try to convert data types to make things work
- Sometimes this is helpful, sometimes it's not
- In this case it creates nonsense
- R will sometimes do this silently inside of a function if you give it the wrong data type
- This can lead to confusing errors
- Try to keep data types in mind
```{r}
my_numbers <- factor(c("14", "36", "44", "912"))
my_numbers
plot(as.numeric(my_numbers))
as.numeric(as.character(my_numbers))
```
### colnames()/rownames()
- Get row or column names for a data.frame
- Returns a vector of characters
```{r}
rownames(mtcars)
colnames(mtcars)
```
## Activity
### if loops
Make a variable called "my_name" and set it to your name
Then write an if loop that prints out "Hello, my name is [your name]" if the variable is equal to your name
```{r}
```
Copy that loop into the chunk below and add an else statement that prints out "That's not my name" if the variable is not equal to your name
Test this out by changing your variable a couple times
```{r}
```
### For loops
Make a vector of your friends' names and write a for loop to print out each name
```{r}
```
Make a for loop to print out the column names of mtcars
```{r}
```
### While loops
Make a variable with your favorite number
Make another variable with the number 1 in it
Write a while loop that prints out each number starting with your starting variable (1) and stops when it reaches your favorite number
```{r}
```
Remember to add 1 to the variable in each iteration of the loop above so it doesn't get stuck on 1 forever!
Write a while loop that can never end (infinite loop)
Stop it (hit the stop sign in the upper right) after it's going for a bit and then think about why it was infinite. How could you change this so it is no longer infinite?
```{r}
```
### Nesting loops
Copy your for loop from above that prints out your friends' names into the chunk below.
Make a new variable that has the name of your best friend (who should be in your list of friends).
Inside of your for loop, write an if statement to check if this friend is your best friend. If they are, print out "[name here] is my best friend!".
Next add an else statement that prints out "[name here] is just a friend." if they're not your best friend.
```{r}
```
We're going to write the wells in a 96 well plate. Using loops!
Make a variable with A through H in it. Make another variable with 1 through 12 in it. Write a for loop that goes over the letters and prints them out.
After that works, put another for loop inside of the first that loops over the numbers. Inside of this second loop print out the letter and number together (e.g. "A1", "A2", etc.).
```{r}
```
## Advanced Activity
- These activities will be a bit of synthesis of stuff from previous days
- use `starwars <- starwars` to get pre-loaded practice data
- Make a new data frame by getting rid of the "films", "vehicles" and "starships" columns using `select()`
- Write a for loop to loop over the column names in your new variable
- Start by just printing out the column name in each iteration of the loop
- Next, write an if loop inside the for loop that checks if the current column contains numeric data and prints out "This column contains numeric data" if it does
- Once that works, add an else statement after your if loop that prints out "This column does not contain numeric data" if the column does not contain numeric data
- Next, if the column contains numeric data, make a histogram of it
- Otherwise, use `table()` to get counts of categories
- Look at the help documentation for `table()` to see how to use it
- If you're super fast:
- Help someone who is struggling (loops can be confusing)
- Write a while loop to count the sum of all integers whose squared value is less than 1,234,567
- You should get 617,716
### Get the starwars data and look at it
library(tidyverse) # load the tidyverse library
starwars <- starwars # to get data
### Write a for loop using over the columns of the subset starwars data frame (after you get rid of the "films", "vehicles" and "starships" columns using select())
Inside the loop, if the column contains numeric data, make a histogram of it
Otherwise, use table() to get counts
- Useful ideas/functions here:
- is.numeric()
- this_column_name <- "height"
- starwars[[this_column_name]] # same as starwars$height to select a column
## If you're super fast:
Help someone who is struggling (loops can be confusing)
### Write a while loop to sum of all numbers whose squared value is less than 1,234,567
1^2 < 1,234,567 # add 1 to sum total
2^2 < 1,234,567 # add 2 to sum total
3^2 < 1,234,567 # add 3 to sum total
.
.
.
X^2 > 1,234,567 # stop here