The Big R-Book. Philippe J. S. De Brouwer
x <- ‘b’ x_info <- switch(x, ‘a’ = “One”, ‘b’ = “Two”, ‘c’ = “Three”, stop(“Error: invalid `x` value”) ) # x_info should be ‘two’ now: x_info ## [1] “Two”
The switch statement can always be written a an else-if statement. The following code does the same as the aforementioned code.
x <- ‘b’ x_info <- if (x == ‘a’ ) { “One” } else if (x == ‘b’) { “Two” } else if (x == ‘c’) { “Three” } else { stop(“Error: invalid `x` value”) } # x_info should be ‘two’ now: x_info ## [1] “Two”
The switch()
statement can always be written as with the if-else-if construction, which in its turn can always be written based on with if-else statements. This is same logic also applies for loops (that repeat parts of code). All loop constructs can always be written with a for-loop and an if-statement, but more advanced structures help to keep code clean and readable.
4.5.2 Loops
One of the most common constructs in programming is repeating a certain block of code a few times. This repeating of code is a “loop.” Loops can repeat code a fixed number of times or do this only when certain conditions are fulfilled.
4.5.2.1 The For Loop
for
loop – for
As in most programming languages, there is a “for-loop” that repeats a certain block of code a given number of times. Interestingly, the counter does not have to follow a pre-defined increment, the counter will rather follow the values supplied in a vector. R's for-loop is an important tool to add to your toolbox.
The for-loop is useful to repeat a block of code a certain number of times. R will iterate a given variable through elements of a vector.
Function use for for()
for (value in vector) { statements }
The for-loop will execute the statements for each value in the given vector.
Example: For loop
x <- LETTERS[1:5] for ( j in x) { print(j) } ## [1] “A” ## [1] “B” ## [1] “C” ## [1] “D” ## [1] “E”
Unlike most computer languages, R does not need to use a “counter” to use a for-loop.
x <- c(0, 1, -1, 102, 102) for ( j in x) { print(j) } ## [1] 0 ## [1] 1 ## [1] -1 ## [1] 102 ## [1] 102
4.5.2.2 Repeat
repeat()
The repeat-loop will repeat the block of commands till it executes the break
command.
loop – repeat
Function use for repeat()
repeat { commands if(condition) {break} }
Example: Repeat loop
x <- c(1,2) c <- 2 repeat { print(x+c) c <- c+1 if(c > 4) {break} } ## [1] 3 4 ## [1] 4 5 ## [1] 5 6
Do not forget the {break} statement, it is integral part of the repeat loop.
4.5.2.3 While
The while-loop is similar to the repeat-loop. However, the while-loop will first check the condition and then run the code to be repeated. So, this code might not be executed at all.
while
loop – while
Function use for while()
while (test_expression) { statement }
The statements are executed as long the test_expression is TRUE.
Example: While loop
x <- c(1,2); c <- 2 while (c < 4) { print(x+c) c <- c + 1 } ## [1] 3 4 ## [1] 4 5
4.5.2.4 Loop Control Statements
When the break
statement is encountered inside a loop, that loop is immediately terminated and program control resumes at the next statement following the loop.
break
v <- c(1:5) for (j in v) { if (j == 3) { print(“--break--”) break } print(j) } ## [1] 1 ## [1] 2 ## [1] “--break--”
The next
statement will skip the remainder of the current iteration of a loop and starts next iteration of the loop.
v <- c(1:5) for (j in v) { if (j == 3) { print(“--skip--”) next } print(j) } ## [1] 1 ## [1] 2 ## [1] “--skip--” ## [1] 4 ## [1] 5
Digression – The speed of loops
The code base of R has been improved a lot and loops are faster than they used to be, however, there can still be a significant time difference between using a loop or using a pre-implemented function.
n <- 10∧7 v1 <- 1:n # -- using vector arithmetic t0 <- Sys.time() v2 <- v1 * 2 t1 <- Sys.time() - t0 print(t1) ## Time difference of 0.06459093 secs # -- using a for loop rm(v2) v2 <- c() t0 <- Sys.time() for (k in v1) v2[k] <- v1[k] * 2 t2 <- Sys.time() - t0 print(t2) ## Time difference of 3.053826 secs # t1 and t2 are difftime objects and only differences # are defined. # To get the quotient, we need to coerce them to numeric. T_rel <- as.numeric(t2, units = “secs”) / as.numeric(t1, units = “secs”) T_rel ## [1] 47.27949
Note that in our simple experiment the for-loop is 47.3 times slower than the vector