# Loops in R

## for Loops

### How for loop works

• A for loop repeats a chunk of code many times, once for each element in a set of input.
for (value in that) {
this
}
• The that object should be a set of objects (often a vector of numbers or character strings).
• 1:10
• 1:length(x)
• 1:nrow(x)
• c("hello", "this", "is", "a", "vector", "of", "strings")
for (value in c("My", "first", "for", "loop")) {
print("one run")
}
## [1] "one run"
## [1] "one run"
## [1] "one run"
## [1] "one run"
• The value symbol in a for loop acts like an argument in a function.
• The for loop will create an object named value and assign it a new value on each run of the loop.
• The code in your loop can access this value by calling the value object.
for (value in c("My", "second", "for", "loop")) {
print(value)
}
## [1] "My"
## [1] "second"
## [1] "for"
## [1] "loop"
• Example: What will be the value of a after the loop?
a <- 100

for (a in 1:5) {
print(a)
}

a

### Exercise 1

• Task: Write a for loop to compute the sum of 5 numbers that are randomly selected from 1 to 100 with replacement.

• First, let’s generate the 5 random numbers!

set.seed(385)
nums <- sample(x = 1:100, size = 5, replace = TRUE)
nums
## [1]  6 90 87 82 16
• Second, write the for loop.
for (i in nums) {
}
• BUT wait! We need something to store the sum.
total <- 0
for (i in nums) {
total <- total + i
}
total
## [1] 281
• Another way to write the for loop.
total <- 0
for (i in 1:length(nums)) {
total <- total + nums[i]
}
total
## [1] 281
• Checking the result using R built-in function:
sum(nums)
## [1] 281

### Working with for loop

• To save output from a for loop, you must write the loop so that it saves its own output as it runs.
• What that means:
• Create an empty vector or list before you run the loop.
• Use the for loop to fill up the vector or list.
• When the for loop is finished, you’ll be able to access the vector or list, which will now have all of your results.

### Exercise 2

• From a given list of fruits, select only the ones that have 6 or fewer letters.
fruits <- c("apple", "pineapple", "watermelon", "orange", "peach", "plum",
"honeydew", "banana", "kiwi", "papaya", "grapes", "strawberry",
"blueberry", "blackberry")
• Create an empty vector to store the final results
fruits_short <- vector(length = length(fruits))
fruits_short
##  [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
## [13] FALSE FALSE
• Write the for loop
for (i in 1:length(fruits)) {
fruit <- fruits[i]
if (nchar(fruit) <= 6) {
fruits_short[i] <- fruit
}
}

fruits_short
##  [1] "apple"  "FALSE"  "FALSE"  "orange" "peach"  "plum"   "FALSE"  "banana"
##  [9] "kiwi"   "papaya" "grapes" "FALSE"  "FALSE"  "FALSE"
• This is not what we want! So let’s try something else!
fruits_short <- c()
count <- 1

for (i in 1:length(fruits)) {
fruit <- fruits[i]
if (nchar(fruit) <= 6) {
fruits_short[count] <- fruit
count <- count + 1
}
}

fruits_short
## [1] "apple"  "orange" "peach"  "plum"   "banana" "kiwi"   "papaya" "grapes"
• The result looks good! But is it sufficient? We will answer that question on Friday.

### How while loop works

• A while loop reruns a chunk while a certain condition remains TRUE.
while (condition) {
code
}
• while will rerun condition (a logical test) at the start of each loop:
• If condition evaluates to TRUE, while will run the code between its braces.
• If condition evaluates to FALSE, while will finish the loop.
• Why might condition change from TRUE to FALSE?
• The code inside the loop changes the certain values which change the result of condition. (We will look at an example next)
• If the code has no relationship to the condition, a while loop will run until you stop it.
• Called infinite loop.
• Example:
cash <- 20
n <- 0

while (cash > 0) {
cash <- cash - 1
n <- n + 1
}

n
## [1] 20
• Another example: Remember the game King of Hearts from Lab02? It costs $1 to play this game each time. If we win a jackpot, we gain$10. Let’s say we start with $20! How long can we play until we run out of money? # from lab02 deck <- read.csv(file = "https://nkha149.github.io/stat385-sp2020/files/data/cards.csv") deck$jackpot <- FALSE
deck[deck$face == "king" & deck$suit == "hearts", 4] <- TRUE

win_jackpot <- function() {
cards <- deck[sample(1:nrow(deck), size = 4), ]
any(cards$jackpot) | (length(unique(cards$face)) == 1) | (length(unique(cards\$suit)) == 1)
}
set.seed(385)

cash <- 20
n <- 0

while (cash > 0) {
cash <- cash - 1
if (win_jackpot()) {
cash <- cash + 10
}
n <- n + 1
}

n
## [1] 40

## repeat Loops

• The repeat loops repeat a chunk of code until you tell them to stop (by hitting Escape) or until they encounter the command break, which will stop the loop.

• We can use a repeat loop to recreata a loop for the example above.

set.seed(385)

cash <- 20
n <- 0

repeat {
cash <- cash - 1
if (win_jackpot()) {
cash <- cash + 10
}
n <- n + 1
if (cash <= 0) {
break
}
}

n
## [1] 40