-
Notifications
You must be signed in to change notification settings - Fork 0
/
CH7_control_flow_loops_and_functions.qmd
1855 lines (1049 loc) · 48.5 KB
/
CH7_control_flow_loops_and_functions.qmd
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
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "Chapter 7 - Control Flow, Loops and Functions"
author: "Government Analysis Function and ONS Data Science Campus"
engine: knitr
execute:
echo: true
eval: true
freeze: auto # re-render only when source changes
---
> To switch between light and dark modes, use the toggle in the top left
```{r}
#| message: false
#| warning: false
#| include: false
library(kableExtra)
```
# Introduction
We use R because it's great for data analysis, data visualisation communicating results. However, R is not just a data analysis environment but a programming language. Advanced R programmers can develop complex packages and even improve R itself.
In this chapter, we introduce three key programming concepts: **loops, conditional statements, and functions**. These are not just key building blocks for advanced programming, but are sometimes useful during data analysis.
## Learning Outcomes
By the end of this chapter you should be able to:
* Understand the programming concept of loops.
* Use loops and understand their place in R.
* Be able to use conditional statements: *if*, *else* and *else if*.
* Be familiar with *else_if()* and *case_when()* from *dplyr*.
* Know what functions are and why they are useful.
* Be able to distinguish between a function's parameters and arguments.
* Including different types of arguments
* Understand the idea of 'scope'.
* i.e. Global scope vs Local scope
* Be able to write and apply user defined functions.
* Be able to apply functions to **vector** and **`tibble`** objects.
The chapter assumes familiarity with:
* Logical Operators such as less than (<) , greater than (>), equivalent to (==) etc
* Knowledge of reading in data (using readr); basic data manipulation (using dplyr)
* General basic knowledge of R code - this course should not be your first introduction to the language.
# Packages and Datasets
## Packages
Below find listed the packages used in this course. This course has been tested with the versions listed.
This course uses various packages from the Tidyverse collection of packages. These can be loaded individually or as a whole through **library(tidyverse)**
* readr - version 1.4.0
* dplyr - version 1.0.6
* purr - version 0.3.4
Other Packages
* janitor - version 2.1.0
* fs - 1.5.0
```{r}
library(tidyverse)
library(janitor)
library(fs)
```
## Data
In this course we will use the data **`titanic_clean.csv`** and assign it to `titanic`
In this file missing values have been specified and headers have been cleaned already for you.
```{r}
titanic <- readr::read_csv("Data/titanic_clean.csv")
```
To Inspect the data we can use:
```{r}
dplyr::glimpse(titanic)
```
<br>
We can see these these are columns,
* **Pclass**: Passenger’s class, 1 = 1st (Upper), 2 = 2nd(Middle), 3 = 3rd(Lower)
* **Survived**: Survived (1) or died (0), 0 = No, 1 = Yes
* **Name**: Passenger’s name
* **Sex**: Passenger’s sex
* **Age**: Passenger’s age
* **SibSp**: Number of siblings/spouses aboard
* **Parch**: Number of parents/children aboard
* **Ticket**: Ticket number
* **Fare**: Fare
* **Cabin**: Cabin number
* **Embarked**: Port of embarkation, C = Cherbourg, Q = Queenstown, S = Southampton
We can see more details on the [Data Dictionary](https://www.kaggle.com/c/titanic/data)
# Loops
Loops are a fundamental concept in traditional programming languages.
A loop is a way to repeat a number of commands until a given condition is met.
This repetition of code is called **iteration**.
A repetitive action could be "create several similar plots".
Within a loop, any other code can be run to produce anything we want such as plots, models, reports, and datasets.
Since R is a vectorised language, loops are not as prominently used in R as in Python or other programming languages. Despite this, they are a key part of programming in general and can save you a large amount of time and typing in certain cases.
They allow you to automate parts of your code that are in need of repetition.
Similar to how functions help make our code more abstract and general, loops perform a similar purpose. We are essentially simplifying a specific case of code to a more general case.
We are going to look at `for` loops first.
## For Loops
These are the most common type of loop the other type is a `while` loop which can do the same things, but in a slightly different way.
For loops follow the basic structure below.
```{r}
#| eval: false
# Basic Structure of a loop
# Creating the loop
for (each_item in my_iterable) {
output <- commands
}
```
* We start the loop with the word `for`,
* Followed by `()` brackets where we first specify an index variable, `i` is commonly used but it can be anything that you want. Remember, we want to use clear and descriptive variable names. This is a place holder and corresponds to each different element as we move through the loop,
* Then the word `in`.
* Then specify an iterable. This could be a `vector`, a `list`, a `dataframe` etc. An iterable is any object that can be iterated through, one element at a time.
* Followed by the `{}` curly brackets, which will have our commands within, these could be multiple lines of code.
### Example
Let's look at an example.
We start by creating an iterable, I have created a vector with the numbers **0 through 5**.
```{r}
# Creating a vector
example_vector <- c(0, 1, 2, 3, 4, 5)
```
We can then create our loop which doubles every value and prints it out.
```{r}
# Creating the loop
for (each_number in example_vector) {
# Print the value at each step
print(each_number * 2)
}
```
![Basic for loop as detailed in the previous exercise](Images/for_loop.png)\
In the above example we simply printed our results in the console, if we wanted to store our result, we can simply create a data structure of our choice and use the append function, as shown below.
The keyword `for` is followed by a variable that refers to each item in my iterable. I’ve called this variable **`each_number`**. It is good to be clear and explicit when naming variables, so they explain what the variable is.
The keyword `in` is followed by the iterable I want to loop over - `example_vector`.
The output of my command is appended to `result`. The command here is to multiply each number in `example_vector` by 2. The **`append()`** function simply adds an element to the end of a vector. We first specify the vector we want to add to which is `result` and then specify the values that we want to add to it. Within the function this is set to the parameter `values`.
```{r}
# Create an empty output
# Which we will fill when the loop runs
result <- c()
# Creating the loop
for (each_number in example_vector) {
# Print the value at each step
print(each_number * 2)
result <- append(result, values = each_number * 2)
}
# To display the data
result
```
<br>
Although it is useful to know how to use loops in R, it is often faster to accomplish the same thing using vectorised operations in R.
We already saw examples in the Vector Arithmetic section. A vectorised function is a function that will apply the same operation on each element of the vectors.
For example:
```{r}
# Creating a vector
example_vector <- 1:5
# Using a sqrt() function on our vector
sqrt(example_vector)
```
<br>
To make this calculation, there is no need for a loop. However, not all functions work this way.
While there are many functions out there that vectorise particular calculations, there are still some tasks that cannot be vectorised. This is where iteration becomes useful. While we should always be looking to vectorise calculations, we can take comfort knowing that we have a back up tool to use just in case it fails us.
We also have while loops, which are used to loop until a specific condition is met.
You can a find a tutorial on them here: [While Loop](https://www.datamentor.io/r-programming/while-loop/).
### Exercise 1
::: {.panel-tabset}
#### Exercise
1. You are given a vector of measurements that are grams (g).
For this exercise, we want to convert all of these measurements to kilograms (kg).
**For reference, 1kg is equal to 1000 grams.**
Using a for loop, create and append to a new vector called **kilograms** that contains the values converted to kilograms.
```{r}
# Vector
grams <- c(100000, 7899900, 967312, 49185, 6100)
```
#### Hint
Please note below is pseudocode, that is the 'recipie' for getting the answer.
```{r}
#| eval: false
# Starting vector
grams <- c(100000, 7899900, 967312, 49185, 6100)
# Empty vector for result storage
kilograms <- c()
# For loop
for (each_number in vector) {
convert to kilograms
append result to kilograms
}
# To display the data
kilograms
```
#### Answer
```{r}
# Starting vector
grams <- c(100000, 7899900, 967312, 49185, 6100)
# Empty vector for result storage
kilograms <- c()
# For loop
for (measurement in grams) {
# Converting grams to kg
converted_kilogram <- measurement / 1000
# Appending to kilo_grams result vector
kilograms <- append(kilograms, values = converted_kilogram)
}
# To display the data
kilograms
```
:::
### Extension Exercise
If you would like to go deeper into for loops before moving on, try the extension exercise below.
::: {.panel-tabset}
#### Exercise
1. Complete the code below, Use a for loop to load all the files in the data folder. Some steps have been given to you already.
* We have loaded the packages tidyverse and fs
* We then use the function `fs::dir_ls()` which will give a list of all the file paths in the data folder, we have assgined this to `file paths`.
* We have created an empty list called `my_datasets` which we fill with out datasets after the loop runs.
* Your task is to create a for loop to loop through the `file_paths` and store each dataset as an element in the list `my_datasets`
```{r}
# Loading packages
library(tidyverse) # For loading data and manipulation of data
library(fs) # File system
# Get a list of the file paths
file_paths <- fs::dir_ls("Data")
# Display the file paths
file_paths
# Create a list to store all the dataframes
my_datasets <- list()
```
#### Hint
```{r}
#| eval: false
# Loading packages
library(tidyverse) # For loading data and manipulation of data
library(fs) # File system
# Get a list of the file paths
file_paths <- fs::dir_ls("Data")
# Display the file paths
file_paths
# Create a list to store all the dataframes
my_datasets <- list()
# Loop through file paths and store in the list
for (each_file_path in file_paths){
# adding a new element in the my datasets list
my_datasets <- command
}
```
#### Show Answer
```{r}
#| message: false
#| warning: false
library(tidyverse) # For loading data and manipulation of data
library(fs) # File system
# Get a list of the file paths
file_paths <- fs::dir_ls("Data")
# Display the file paths
file_paths
# Create a list to store all the dataframes
my_datasets <- list()
# Loop through file paths and store in the list
for (each_file_path in file_paths){
# adding a new element in the my datasets list
my_datasets[[each_file_path]] <- readr::read_csv(file = file_paths[[each_file_path]])
}
# To display the list of dataframes
dplyr::glimpse(my_datasets)
```
If you want the datasets to be displayed as separate datasets in the environment window, you can use the `list2env()`, here we specify the list `my_datasets` and the argument `envir=.GlobalEnv`.
```{r}
# To display in environment as separate datasets
list2env(my_datasets,envir=.GlobalEnv)
```
Like we said lists are the not the only way to do this, other options would be to use the `lapply()` or the `purrr::map()` function.
To use either of these functions all we need is to provide the file path list and then the function we want to run on the list.
>**Please note that when we use the function inside lapply or map we don't include the brackets as we are not passing any inputs into the function, hence we read_csv instead of read_csv(), so lapply/map is the function and read_csv is like an input/argument**
```{r}
#| eval: false
#|
# Using lapply to load multiple files
my_datasets <- lapply(file_paths, read_csv)
# Using lapply to load multiple files
my_datasets <- purrr::map(file_paths, read_csv)
```
As you can see that we can we achieve the same result as the loop.
:::
## While loops
Our other type of loops is the `while` loop.
`for` loops iterate a set amount of times, or over a set number of things. A `while` loop iterates until it no longer meets a certain condition.
```{r}
#| eval: false
# Create an empty output
# Which we will fill when the loop runs
result <- c()
# Creating the loop
while (logical_condition) {
result <- commands
}
# To display the data
result
```
* So we start with creating an empty vector for our output
* Then the word `while`
* followed by the `()` brackets in which we specify our logical condition, using the **conditional operators**.
* and then `{}`, which surrounds our commands. These commands will be run repeatedly in order as long as the specified condition is `TRUE`.
### Example
Let's look at an example:
- Let us first set the `stop_value` to 0.
- and we set our condition to be `stop_value < 5`
- then print out the value of `stop_value`
- and then add one to the value.
```{r}
# Create an empty output
# Which we will fill when the loop runs
result <- c()
# Setting the value
stop_value <- 0
# Creating the loop
# Our condition here is that stop_value < 5
while (stop_value < 5) {
print(stop_value)
stop_value <- stop_value + 1
result <- append(result, stop_value + 1)
}
# To display the data
result
```
Can you guess what would happen if we removed the `stop_value <- stop_value + 1` ?
```{r}
#| eval: false
# Create an empty output
# Which we will fill when the loop runs
result <- c()
# Setting the value
stop_value <- 0
# Creating the loop
# Our condition here is that 0<5 i.e stop_value
while (stop_value < 5) {
print(stop_value)
result <- append(result, values = stop_value + 1)
}
# To display the data
result
```
If we removed the code `stop_value <- stop_value +1` , `stop_value` (`0`) would always be less than `5` and the loop would be stuck in an infinite loop, as R will never stop running the code!
>**You will have to hit the stop sign to exit the loop!**
It is therefore important that we design `while` loops that have a logical condition that will be met at some point.
Although it is useful to know how to use loops in R, it is often faster to accomplish the same thing using vectorised operations in R.
We already saw examples in the Vector Arithmetic section. A vectorized function is a function that will apply the same operation on each of the vectors.
For example,
```{r}
# Creating a vector
example_vector <- 1:5
# Using a sqrt() function on our vector
sqrt(example_vector)
```
To make this calculation, there is no need for a loop. However, not all functions work this way.
## Exercise
::: {.panel-tabset}
### Exercise
1. Code a `while` loop with the following characteristics:
- Assign the value of a variable `temperature` to be 40.
- The condition of the `while` loop should check if the temperature is higher than `20`
- The first command in the body should print out `"Its way too hot!"`
- The next command should decrease the `temperature` by `2` and assign this new value to `temperature` again.
### Hint
```{r}
#| eval: false
# Create an empty output
# Which we will fill when the loop runs
result <- c()
# Setting the temperature value
temperature <- 40
# Code the while loop
while (condition) {
conditions
result <- append(result, temperature)
}
# To display the data
result
```
### Show Answer
```{r}
# Create an empty output
# Which we will fill when the loop runs
result <- c()
# Setting the temperature value
temperature <- 40
# Code the while loop
while (temperature > 20) {
print("It way too hot!")
temperature <- temperature - 2
result <- append(result, temperature)
}
# To display the data
result
```
:::
# Conditional Statements
## If, else if, else
A conditional statement will check whether a statement is `TRUE` or `FALSE`.
If a criteria is met, we may want to run different code than if it is not met.
This is useful if we want a function or code block to run only when our data meets certain conditions; this is termed `control flow`.
Control flow is something we do in everyday life.
For example when we go shopping and choose fruits, we normally want to buy the ones that look juicy and healthy and avoid the ones that look rotten or bruised.
As we pick up our fruit and inspect it, we are actually using control flow.
![Conditional statements checking whether a fruit is suitable to purchase](Images/control_flow_image.png)\
In order to move through this decision process, we need to answer either "Yes" or "No" to each question.
A series of "Yes" answers will lead us to buy an orange that matches our set criteria.
This links in with the logical or Boolean data types that we covered in **Chapter One, Getting Started With R**, as our logical statement has to be either `TRUE` or `FALSE`.
To evaluate these we use comparison operators which we used in **Chapter 4 Working With Dataframes** where we used the `filter()` function.
These comparison and logical operators allow us to control the flow of our code.
**Comparison Operators.**
| Operator | Description |
| ------ |:------|
| == | equal to |
| != | not equal to |
| < | less than|
| > | greater than |
| <= | less than or equal to|
| >= | greater than or equal to|
**Logical Operators.**
| Operator| Description|
| ------ |:------:|
| & | And |
| \| | Or |
| ! | Not|
| Condition 1 | Condition 2 | & (AND) Equates to | | (OR) Equates to |
|:-----------:|:------------:|:------------------:|:------------------:|
| True | True | True | True |
| True | False | False | True |
| False | True | False | True |
| False | False | False | False |
Our example above shows that we can make a decision by answering "Yes" or "No" at two key points. But often this will not be the case - we might have only a single question, or we might want to add some more branches to our responses.
R allows us to have complete control over our statement by using the `if`, `else if`, and `else` keywords.
We always first put an:
- `if` statement
then an optional number (0 to many) of:
- `else if` statements
then finally an optional singular:
- `else` statement
`if`, `else if` and `else` are not loops, but fall under the category of control flow.
These take a conditional argument, and if that is met (evaluates to `TRUE`) then the associated action is completed.
If the condition is not met it will move to the next statement and try to evaluate it; if that condition is met the associated action will be completed.
Finally, if none of the conditions are met, the `else` condition's associated actions are run.
We separate out out different command blocks relating to each condition using curly brackets `{}` around the corresponding block of code.
```{r}
#| eval: false
if (first_condition) {
execute_this
} else if (second_condition) {
execute_this
} else {
execute_this
}
```
> **It’s important that the `else if` keyword comes on the same line as the closing bracket of the previous part of the control structure.**
![Simple if, else if, and else diagram](Images/control_flow_if_elseif_and_else.png)\
Let's look at an example.
We can just have an `if` and an `else` - `else if` statements are optional (as is the final `else` statement!)
```{r}
height <- 5
if (height == 5) {
print("We're the same height")
} else {
print("Your height is different")
}
```
Remember our `if`, `else if` and `else` statements take a condition so we need a double equals sign `==` for checking equivalence.
If the first criteria isn’t met it will move to the else statement and action that.
We can add in more choices using an `else if` statement.
```{r}
height <- 7
if (height == 5) {
print("Your height is 5")
} else if (height == 7) {
print("We are the same height")
} else {
print("Your height is not 5 or 7")
}
```
Within our condition we can use the logical operators too: `&` (and); `|` (or), in order to make more complex conditions.
Here we want the action to happen if the value is greater than 7 and less than 10.
```{r}
height <- 9
if (height == 5) {
print("Your height is 5")
} else if (height > 7 & height < 10) {
print("You're height is between 7 and 10")
} else {
print("Your height is different")
}
```
It’s important to know how the `if`, `else if`, `else` works.
Below we have two options for when the value is 5. However it will only print out “We’re the same height!” as when a condition is met, the code associated with it is run, and R stops evaluating the rest of the conditionals.
In this code the block `print("Wow, it's still 5!")` will never run. If the height is equal to `5`, the first `if` condition will run, and then the logic stops.
Try changing the value stored in `height` to see the other results.
```{r}
height <- 5
if (height == 5) {
print("We're the same height")
} else if (height > 7 & height < 10) {
print("You're tall!")
} else if (height == 5) {
print("Wow, it's still 5!")
} else {
print("Your height is different")
}
```
>**A good practical example of if and else statements can be seen here [PHE](https://github.com/publichealthengland/excess-deaths/blob/master/R/function_visualisations.R)**
## Loops and Conditional Statements
We can combine a `loop` with `if else` statements.
* We have a vector, with values from `1-7` and assign it to `number_of_takeaways_ordered`.
* And a `for` loop with an `if` and `else` statement which shows that if you order more than `2` takeaways a week it will print `"too many"` and if you order less than two it prints `"enough"`.
```{r}
number_of_takeaways_ordered <- c(1, 2, 3, 4, 5, 6, 7)
for (number in number_of_takeaways_ordered) {
print(number)
if (number > 3) {
print("too many")
} else {
print("enough")
# We have a loop, and else if statements, which means we
# need to careful about our closing brackets!
}
}
```
### Extension Exercise: FizzBuzz
::: {.panel-tabset}
#### Exercise
1. Can you write a loop with an `if`, `else if` and `else` statement, that loops through the numbers from 1 to 30.
If the number is a multiple of both 3 and 5, print "FizzBuzz".
If the number is a multiple of 3, print the word "Fizz".
If the number is a multiple of 5, print the word "Buzz".
For all other values print the number.
Note: You can use the modulus operator for this - this is the **`%%`** in R, and shows us our remainder.
For example checking if something is divisible by 3 we can do:
```{r}
# Example of Modulo
# Returns FALSE (10 / 3 has a remainder of 1 - so does not have a remainder of 0)
10 %% 3 == 0
```
```{r}
# Second example of Modulo
# Returns TRUE (9 / 3 has a remainder of 0)
9 %% 3 == 0
```
#### Hint
```{r}
#| eval: false
for (each_number in vector) {
if (first_conditions) {
output
} else if (second_condition) {
output
} else if (third_condition) {
output
} else {
print(each_number)
}
}
```
#### Show Answer