The Big R-Book. Philippe J. S. De Brouwer
Чтение книги онлайн.
Читать онлайн книгу The Big R-Book - Philippe J. S. De Brouwer страница 37
![The Big R-Book - Philippe J. S. De Brouwer The Big R-Book - Philippe J. S. De Brouwer](/cover_pre848614.jpg)
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 operation! So, use operators at the highest level (vectors, matrices, etc) and especially do an effort to understand the apply
-family functions (see Chapter 4.3.5 “Arrays” on page 50) or their tidyverse equivalents: the map
-family of functions of the package purrr
. An example for the apply-family can be found in Chapter 22.2.6 on page 513 and one