Intro to Data Science

Lecture 7 – Code Iteration

A Guide to Your Process

Scheduling

Learning Objectives

Practice

Supporting Information

Class Discussion

Today’s Plan

  • Code Iteration with Loops
  • Conditionals in Loops
  • In-Class Free Work

Today’s Learning Objectives

After today’s session you will be able to:

  • Describe the contexts where iteration is useful
  • Apply loops to small arithmetic problems
  • Create a loop with a conditional

Repeated Operations

  • Often we want to repeat a given operation multiple times
    • I.e., repeat iteratively


  • Could just copy/paste our code for each iteration
    • Labor intensive & inefficient & ugly (IMO)


  • Copy/pasting fails if you need to do something many times
    • Code iteration is our solution to these types of problems!

Code Iteration

  • Iteration process:
    1. Define the operation that you want to repeat
    2. Define the values to be passed through that operation
    3. Press “go” and sit back while the code does the work!


  • Benefits:
    • Much faster than copy/pasting code
    • Code is more human-readable / navigable
    • Allows you to do something else while the code iterates itself!


  • This method is called a “for loop

Loop Syntax

  • For loops repeat an operation for each value given to them


  • Fundamental syntax is as follows:
# Start of loop
for ( index in vector ) {

    # Actual operation of loop
    function(index) 

} # End of loop


  • More info:
    • index = placeholder for one value in vector
    • vector = set of values to pass through loop
    • curly braces ({/}) to define start/end

Loop Example

  • Let’s check out an example loop to get more comfortable with these!


  • Square each integer between 1 and 5
# Loop across vector of numbers
for(k in 1:5){
  
  # Square that number
  square_k <- k * k
  
  # Print that result
  print(square_k)
  
}
[1] 1
[1] 4
[1] 9
[1] 16
[1] 25

Loop Practice

  • Make a vector of numbers between 5 and 25


  • Write a for loop that:
      1. Takes the square root of each number (see ?sqrt)
      1. Prints that result (use print function)

Loop Practice (Answer)

  • Demonstrating on only a few numbers
# Define loop
for(j in 5:8){
  
  # Take square root
  j_root <- sqrt(x = j)
  
  # Print that result
  print(x = j_root)
  
} # Close loop
[1] 2.236068
[1] 2.44949
[1] 2.645751
[1] 2.828427

More Loop Practice

  • Write a second loop that:
    1. multiplies each number by 32
    2. Prints the result in the console


  • Answer:
for(i in 5:25){
  i_mult <- i * 32
  print(i_mult)
}

Temperature Check

How are you Feeling?

Comic-style graph depicting someone's emotional state as they debug code (from initial struggle and defeat to eventual triumph)

Messaging with R

  • By default, loops don’t put stuff in the Console
    • This can make figuring out what is going on difficult


  • Fortunately, R contains functions for putting text into the Console
    • print is the one we’ll focus on!


  • However, print only accepts one vector at a time


  • paste makes multiple vectors into one vector

Message Example

  • Let’s consider an example of a loop that uses print and paste to make messages


  • For instance:
# Loop across vector of numbers
for(k in 1:5){
  
  # Square that number
  square_k <- k * k
  
  # Print a message about that result
  print(paste("The square of", k, "is", square_k))

}
[1] "The square of 1 is 1"
[1] "The square of 2 is 4"
[1] "The square of 3 is 9"
[1] "The square of 4 is 16"
[1] "The square of 5 is 25"

Write Messages

  • We’ll modify your earlier practice loops to make informative messages!


  • For the loop that takes the square root of the index:
    • Make the print step tell you the starting number and its square root


  • Answer:
for(j in 5:25){
  j_root <- sqrt(j)
  print(paste("The square root of", j, "is", j_root))
}

More Message Practice

  • For the loop that multiplies the index by 32:
    • Write a message that says each number and what it times 32 is equal to


  • Answer:
for(i in 5:25){
  i_mult <- i * 32
  print(paste(i, "times 32 is equal to", i_mult))
}

Temperature Check

How are you Feeling?

Comic-style graph depicting someone's emotional state as they debug code (from initial struggle and defeat to eventual triumph)

Conditionals

  • You can write code to do something only if some condition is met
    • Do this by using conditionals!


  • Syntax is similar to logical statements for subsetting
    • Recall our earlier conversations about conditional operators:
    • ==, &, >, etc.


  • Two main conditional functions: if & else

Conditional Example

# Do something if a condition is met
if(2 == 2){

  print("Math is mathing!")

  # If that condition is not met...
} else { 
  
  print("Math is--somehow--not mathing...")

}
[1] "Math is mathing!"

Conditional Syntax

  • if wants:
    • Condition to check in parentheses (...)
    • What to do if the condition is met in curly braces {...}


  • else wants:
    • Only curly braces {...} bits
    • Can only be used if if is used first


  • The example in the previous slide is just for one if
    • Essentially ‘either this or that

Multiple ifs

  • You can add multiple conditions if desired!


# If the number is less than 0
if(x < 0){

  print("Number is negative")

# If it's more than 0
} else if(x > 0){

  print("Number is positive")

# Otherwise ...
} else { 

  print("Number is zero")

}


  • See how the second condition uses else if(...){...}?

Conditionals in Loops

  • You can use conditionals to make one loop handle multiple possibilities


  • For example:
# Test vector
my_vec <- c(-10, -9, -8, 0, 4, 5, 6)

# Loop across it
for(value in my_vec){
  
  # Make negative numbers positive
  if(value < 0){ 
    print(value * -1)
    
    # Take the square root of positive numbers
  } else if(value > 0){
      print(sqrt(value)) }
  
} # Close loop curly brace
[1] 10
[1] 9
[1] 8
[1] 2
[1] 2.236068
[1] 2.44949

Loop Conditional Visual

Comic showing a loop across a set of monster shapes where triangle creatures get sunglasses but non-triangles get a hat because of an 'if' and 'else' use in the loop

Loops with Conditionals

  • Write a loop that:
    • Uses g as the index
    • Uses a vector that has all the integers between 10 and 20
    • Prints each value in the vector


  • Add two conditionals to that loop:
    1. If g is less than 14, print “Less than 14”
    2. Otherwise, print the value as-is

Temperature Check

How are you Feeling?

Comic-style graph depicting someone's emotional state as they debug code (from initial struggle and defeat to eventual triumph)

In-Class Free Work

  • Draft 2 of Function Tutorials is due next week!
    • Presentations during Lecture #8
    • Requires ‘revision response’ where you discuss what changes you made due to feedback


  • GitHub Presence is due next week
    • You have most of what you need for full points on that already


  • Any questions about upcoming assignments / past topics?
    • I strongly recommend taking advantage of this time!

Upcoming Due Dates

Due before lecture

(By midnight)

  • Homework #7
  • Submit Draft 2 of Function Tutorials
    • Double check rubric to see that you’re not leaving any points on the table!
    • Remember to also submit the Revision Response

Due before lab

(By midnight)

  • Homework #8
  • Muddiest Point #8
  • GitHub Presence