Christian Sekulovic und Julius Schmid
Task: Create a notebook explaining the importance and use of
loops in R-Programming.
This is the final project assignment for the course Program for Data
Analytics (CIS-543). We will discuss the importance of different types
of loops in R, and will present use cases.
First of all, let us begin with the definition of a loop:
Loops are a programming element that repeat a
portion of code a set number of times until the desired process is
complete. Repetitive tasks are common in programming, and loops are
essential to save time and minimize errors.
Further, the programming language R is very good at performing
repetitive tasks. If we want a set of operations to be repeated several
times we use loops. When you create a loop, R will execute the
instructions in the loop a specified number of times or until a
specified condition is met. There are three main types of loops in
R:
- For Loops
- While Loops
- Repeat Loops
Let us now consider each type of loop individually with an
example.
1. For Loops
The purpose of the for loop is to execute a code a fixed number of
times or for each element within a list or vector. The variable which
represents the number of repititions is an integer and is usually
defined with a fixed value at the start of the loop.
Note that a for loop can always be replaced by a vectorized
statement.
The syntax for a for loop is given by “for (k in
lower_bound:upper_bound){code that is repeated while lower_bound <= k
<= upper_bound}”.
Consider the following example for a for loop:
n <- 10
factorial <- 1
for (k in 1:n){
factorial <- factorial * k
print(factorial)
}
[1] 1
[1] 2
[1] 6
[1] 24
[1] 120
[1] 720
[1] 5040
[1] 40320
[1] 362880
[1] 3628800
In this example, we created the factorials of the numbers 1 through
10, using a for loop with running variable k.
2. While Loop
Another type of loop is the while loop. The while loop is used when
you want to keep looping until a specific logical condition is satisfied
(contrast this with the for loop which will always iterate through an
entire sequence).
Since the code within the loop is repeated as long as the statement
is true, you have to be careful that you accidentally produce an
“eternal” loop that never stops in case the statement is always true.
The code then has to be manually terminated to stop it from running
infinitely long.
The syntax for a while loop is given by “while (boolean
statement){code that is repeated while statement is true}”.
Consider an example where we roll a dice and consider it a success
when we roll a 6. We keep rolling until we roll the 6. Admittedly, the
outcome for the dice in this case is independent from any
probabilities.
dice <- 1
while (dice <= 6) {
if (dice < 6) {
print("No success")
} else {
print("Success!")
}
dice <- dice + 1
}
[1] "No success"
[1] "No success"
[1] "No success"
[1] "No success"
[1] "No success"
[1] "Success!"
We execute the code while the outcome of the dice is less than or
equal to 6. At the moment when the dice variable is set to 7 in the last
running period, the statement dice <= 6 becomes false and we quit the
loop.
3. Repeat Loops
A repeat loop is used to iterate over a block of code multiple number
of times. There is no condition check in repeat loop to exit the
loop.
Note that we must ourselves put a condition explicitly inside the
body of the loop and use the break statement to exit the loop. Failing
to do so will result into an infinite loop.
The syntax for a repeat loop is given by “repeat {statement}” where
we need to include an if statement together a “break” when the
if-statement is true. Remember that the if statement necessarily needs
to become true at some point.
Consider the following example:
df <- data.frame(A=c(0,0,0,0),
B=c(0,0,0,0))
x <- 0
repeat{
x <- x+1
df$A[x] <- x
df$B[x] <- x * 2
if(x >= nrow(df)){
break
}
}
Here, we create a data frame with two columns and four rows and use
the repeat loop to fill the data frame with concrete values by
increasing the index variable x by 1 each time we repeat the loop. The
if statement in this case ensures that we only update values in the data
frame that actually exist. The moment that our index variable x becomes
bigger than the number of rows, we call break and exit the repeat
loop.
References:
[1] https://intro2r.com/loops.html
[2] http://support.kodable.com/en/articles/417331-what-are-loop
[3] https://www.w3schools.com/r/r_while_loop.asp
[4] https://www.datamentor.io/r-programming/repeat-loop/
LS0tCnRpdGxlOiAiUHJvamVjdCAyOiBMb29wcyBpbiBSLVByb2dyYW1taW5nIgpvdXRwdXQ6IGh0bWxfbm90ZWJvb2sKLS0tCgpDaHJpc3RpYW4gU2VrdWxvdmljIHVuZCBKdWxpdXMgU2NobWlkCgoqKlRhc2s6IENyZWF0ZSBhIG5vdGVib29rIGV4cGxhaW5pbmcgdGhlIGltcG9ydGFuY2UgYW5kIHVzZSBvZiBsb29wcyBpbiBSLVByb2dyYW1taW5nLioqCgpUaGlzIGlzIHRoZSBmaW5hbCBwcm9qZWN0IGFzc2lnbm1lbnQgZm9yIHRoZSBjb3Vyc2UgUHJvZ3JhbSBmb3IgRGF0YSBBbmFseXRpY3MgKENJUy01NDMpLiBXZSB3aWxsIGRpc2N1c3MgdGhlIGltcG9ydGFuY2Ugb2YgZGlmZmVyZW50IHR5cGVzIG9mIGxvb3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