rm (list=ls())
################################################################
################################################################
##
## Intro to for loop.
##
## A "for loop" is similar to a "while loop" in that it causes a
## body of code to be repeated more than once. The for loop is DIFFERENT
## from the while loop in HOW it accomplishes the repetition.
##
## If you need code to be repeated you can ALWAYS use a WHILE loop.
## However, sometimes the while loop can be a little confusing.
## A "for loop" is an alternative to a "while loop" that is usually easier
## to understand than the equivalent code that uses a while loop
## (we'll explain why later).
##
## Unfortunately, you cannot always use a FOR loop.
## A for loop can only be used if it's possible to know before the loop
## starts exactly how many times the loop will need to
## iterate (i.e. "go around"). The reason for this will be explained later.
##
## It's probably easiest to understand how the for loop works
## if you examine the example code that appears below. However,
## the following is an attempt to explain in words how the for
## loop works. I recommend that you look at the examples below
## and then come back and read this more detailed explanation.
##
## ------------------------------------------------------------
##
## Code of "for loops" is arranged in the following format.
##
## for ( SOME_VARIABLE in SOME_VECTOR__OR__SOME_LIST ){
##
## # statements that
##
## # may refer to
##
## # the variable
##
## }
##
## NOTES:
##
## 1. SOME_VARIABLE is the name of a variable. This variable is created just for
## the purpose of the for loop. You cannot refer to this variable outside
## of the code for the for loop. (If the same name is used for a variable
## outside of the for loop it is a different variable).
##
## 2. SOME_VECTOR__OR__SOME_LIST is a vector or a list.
## This could be a variable name that was created before the
## for loop started or it could be the result a function that creates
## a vector or a list.
##
## 3. The code executes in the following way:
##
## step 1. The first value in the vector (or list) is assigned to the variable.
##
## step 2. The body of the loop (i.e. code between {curly braces}) is executed.
## [The code in the body may refer to the variable but it doesn't have to.]
##
## step 3. After the {body} finishes executing once, the next value from the
## vector (or list) is assigned to the variable.
##
## step 4. The body of the for loop is then executed again.
## However, this time the value of the variable is the 2nd value
## from the vector (or list).
##
## step 5. The for loop keeps replacing the value of the variable with the
## next value from the vector (or list) and then doing the code in
## the {body} until it runs out of values from the vector (or list).
##
## step 6. After all values from the vector (or list) have been processed,
## the loop is finished and execution continues with the line after
## the end of the body of the loop - i.e. the line after the "}"
##
################################################################
################################################################
36 36. for loops
36.1 Example - countdown
# This file goes through several examples of using a for loop and a while loop.
# Be sure to see the notes at the bottom of this file for some important
# concepts and a discussion of when a for loop is an option and when
# you must use a while loop.
#--------------------------------------------------------------------------.
# Example of a for loop
#
# Everything you need to know about a for loop is in the first line of the
# loop (i.e. the line that starts with the word "for").
# In the following example, the first line says: for(num in 10:1).
#
# In this example, num is a variable and 10:1 is a vector,
# i.e. c(10,9,8,7,6,5,4,3,2,1). The for loop automatically assigns a value
# from the vector to the variable. Then it does the body. Then it assigns
# the next value from the vector to the variable and does the body again.
# It keeps doing this until all of the values have been processed by the
# body of the loop. Specifically, in this example:
#
# The 1st value from the vector (i.e. 10) is assigned to the variable, num
# Then the body of the loop is executed.
#
# The 2nd value from the vector (i.e. 9) is assigned to the variable, num
# Then the body of the loop is executed.
#
# The 3rd value from the vector (i.e. 8) is assigned to the variable, num
# Then the body of the loop is executed.
#
# etc ...
#
# The 10th value from the vector (i.e. 1) is assigned to the variable, num
# Then the body of the loop is executed.
#
# At this point, the loop is finished and the function continues with the
# code after the body of the loop.
#--------------------------------------------------------------------------.
<- function (){
countdown for (num in 10:1){ # each time through the loop another value from 10:1 is assigned to num
cat(num," ") # display num followed by a space
Sys.sleep(1.5) # sleep for 1.5 seconds
}
cat("blastoff!") # after the loop has finished, display "blastoff!"
}
countdown()
10 9 8 7 6 5 4 3 2 1 blastoff!
36.2 You can rewrite any for loop as a while loop
#----------------------------------------------------------------------
# A for loop can ALWAYS be rewritten as a while loop.
#
# The following code rewrites the above example to use a while loop.
#
# The while loop version is usually a little harder to understand
# than the for loop version. To understand how many times a for loop will
# iterate (i.e. go around) you just have to look at the first line
# of the for loop.
#
# To understand how the while loop works, you also have to look at the first
# of the loop. However, you also have to track how the variables used
# in the condition of the while loop are changed by the code in the body of
# the while loop.
#----------------------------------------------------------------------
<- function (){
countdownWithWhile = 10 # setup the variables to be used in the condition of the while
num
while(num >= 1){ # condition that's TRUE when loop should run and FALSE when loop should end
cat(num, " ")
Sys.sleep(0.25)
<- num - 1 # change some variable that is part of the condition
num # END OF WHILE - code below will only happen after while finishes
}
cat("blastoff!")
}
countdownWithWhile()
10 9 8 7 6 5 4 3 2 1 blastoff!
36.3 A “for loop” can use ANY vector or list
#----------------------------------------------------------------------
# A "for loop" can use ANY vector or list
#
# Other examples of vectors
# - character and logical vectors
# - numeric vectors that don't count by ones
#----------------------------------------------------------------------
#-----------------------------------------------.
# Count by two's - with a for loop
#-----------------------------------------------.
= function(){
countByTwos_for = seq(2,10, by=2)
vec for ( num in vec){
cat("I like number", num, "\n")
}
}
countByTwos_for()
I like number 2
I like number 4
I like number 6
I like number 8
I like number 10
#-----------------------------------------------.
# rewriting the same example with a while loop
#-----------------------------------------------.
= function(){
countByTwos_while = 2
num while ( num <= 10){
cat("I like number", num, "\n")
= num + 2
num
}
}
countByTwos_while()
I like number 2
I like number 4
I like number 6
I like number 8
I like number 10
36.4 How to convert any for loop into a while loop
#-----------------------------------------------------------------------.
# Any code with a "for loop" can be converted to equivalent code
# with a while loop by following these steps:
#
# step 1: before the while loop copy the vector (or list)
# from the for loop in to a new variable, eg. vecOrList
#
# step 2: create a variable for the position in the vector (or list)
# to be processed at each iteration through the body of the loop
#
# step 3: write the while loop with the condition
# while ( position <= length(vecOrList) )
#
# step 4: Write a line at the end of the body of code for the while loop
# that increments (i.e. adds 1 to) the position variable
#
# We demonstrate this by following these steps to rewrite
# the code from the countByTwos_for function to an equivalent
# function with a while loop.
#-----------------------------------------------------------------------.
# Rewrite the for countByTwos function to use a while loop in a way that
# we can apply the same approach to convert ANY for loop into an
# equivalent while loop. Note that this version is not the same as
# the previous version that used a while loop. Both versions work, but the
# previous version is probably easier to understand. The approach
# taken with this version can be applied to any for loop.
= function(){
countByTwos_while_version2
# step 1: copy the vector from the for loop in to a variable
= seq(2,10, by=2)
vec
# step 2: create a variable for the position in the vector (or list)
# to be processed at each iteration through the body of the loop
= 1
position
while ( position <= length(vec)){ # step 3: write the condition for the while
cat("I like number", vec[position], "\n")
# step 4: at the end of the body of the loop add one to the position
# variable
= position + 1
position
}
}
countByTwos_while_version2()
I like number 2
I like number 4
I like number 6
I like number 8
I like number 10
36.5 — Practice —
##################################################################.
# QUESTION
##################################################################.
#
# Write a function that takes a matrix, m, as an argument.
# The function should return a new matrix that
#
# multiplies the 1st row by 10
# multiplies the 2nd row by 100
# multiplies the 3rd row by 1000
# etc ... for all rows of the matrix
#
# (a) - Write the function using a for loop
# (b) - Write the function using a while loop
#
##################################################################.
##################################################################.
# QUESTION
##################################################################.
#
# Write a function that takes a matrix, m, as an argument.
# The function should return a new matrix that
#
# adds 2 (i.e. 1+1) the value in position 1,1
# adds 3 (i.e. 1+2) the value in position 1,2
# adds 4 (i.e. 1+3) the value in position 1,3
# ... and similarly for the rest of the values in row 1
#
# adds 3 (i.e. 2+1) the value in position 2,1
# adds 4 (i.e. 2+2) the value in position 2,2
# adds 5 (i.e.2+3) the value in position 2,3
# ... and similarly for the rest of the values in row 2
#
# etc ... for all rows in the matrix
#
# Use nested loops for your answer
#
# (a) - Write the function using nested for loops
# (b) - Write the function using nested while loops
# (c) - Write the function using nested loops, one should be a for loop
# and one a while loop (your choice which is which)
#
##################################################################.