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.
- 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")
## [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 namedvalue
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.
## [1] "My"
## [1] "second"
## [1] "for"
## [1] "loop"
- Example: What will be the value of
a
after the loop?
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!
## [1] 6 90 87 82 16
- Second, write the
for
loop.
- BUT wait! We need something to store the sum.
## [1] 281
- Another way to write the
for
loop.
## [1] 281
- Checking the result using R built-in function:
## [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
## [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.
while
Loops
How while
loop works
- A
while
loop reruns a chunk while a certain condition remainsTRUE
.
while
will reruncondition
(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.
- If condition evaluates to
- Why might
condition
change fromTRUE
toFALSE
?- The code inside the loop changes the certain values which change the result of
condition
. (We will look at an example next)
- The code inside the loop changes the certain values which change the result of
- If the code has no relationship to the
condition
, awhile
loop will run until you stop it.- Called infinite loop.
- Example:
## [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 commandbreak
, 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
To-do
- Read Chapter 12: Speed of Hands-On Programming with R.
- Bring your laptop to lecture on Wednesday (02/12/2020) for Lab 03.
- Lab 03 will be posted either late evening on Tuesday or early Wednesday.
References
- Hands-On Programming with R, by Garrett Grolemund.