Oliver Nakoinz, Lizzie Scholtus, Néhémie Strupler
What is control flow?
for()
certain number of repetitionswhile()
as long as a condition is metrepeat()
until we break the loopif()
run some code or notif() else()
run some code or another codeFor loops repeat code a certain times and use an internal iteration variable.
## [1] "Loop no.: 1"
## [1] "Loop no.: 2"
## [1] "Loop no.: 3"
## [1] "Loop no.: 4"
## [1] "Loop no.: 5"
While loops repeat code until a certain condition is met. Iteration variables, if required have to be installed manually.
Analyze Code!
## [1] "Loop no.: 1"
## [1] "Loop no.: 2"
## [1] "Loop no.: 3"
## [1] "Loop no.: 4"
Iteration variable and the variable for the condition need not to be the same.
## [1] "Loop no.: 1"
## [1] "Loop no.: 2"
## [1] "Loop no.: 3"
## [1] "Loop no.: 4"
## [1] "Loop no.: 5"
## [1] "Loop no.: 6"
## [1] "Loop no.: 7"
## [1] "Loop no.: 8"
## [1] "Loop no.: 9"
## [1] "Loop no.: 10"
## [1] "Loop no.: 11"
## [1] "Loop no.: 12"
## [1] "Loop no.: 13"
If allows for conditional code. The condition contains a logical value and can make use of logical operators: ==, !=, <, <=, >, >=
The terms can be combined with and &
and or |
.
Repeat repeats code until we break the loop with break
.
i <- 1
repeat{print(paste("Loop no.: ", i))
i <- i + 1
if(i < 5){next}
print(paste("Value: ", 2^i))
if(i > 10){break}
}
## [1] "Loop no.: 1"
## [1] "Loop no.: 2"
## [1] "Loop no.: 3"
## [1] "Loop no.: 4"
## [1] "Value: 32"
## [1] "Loop no.: 5"
## [1] "Value: 64"
## [1] "Loop no.: 6"
## [1] "Value: 128"
## [1] "Loop no.: 7"
## [1] "Value: 256"
## [1] "Loop no.: 8"
## [1] "Value: 512"
## [1] "Loop no.: 9"
## [1] "Value: 1024"
## [1] "Loop no.: 10"
## [1] "Value: 2048"
If Else tests for a condition. If the condition is True Code 1 is terminated if False execute Code 2.
## [1] "deff"
Functions are container, shortcuts or names for pieces of code. Variables can be passed on to the functions as parameters.
analyze Code!
sqrt()
expects a number as a parameter or operates on a vectormean()
expects a vector as parameter apply
and co.apply
is a function that runs other functions for every column or row of a matrix or dataframe. apply
is usually faster than a loop.
analyze Code!
Which approach do you prefer?
Tidyverse is a philosophy and a style of data sciences within the R ecosphere, initiated by Hadley Wickham (now at RStudio). Tidyverse includes R-packages partly as part of the meta-package tidyverse
. The following slides are mainly based on Wickham/Grolemund (2017): http://r4ds.had.co.nz/.