Intro to Data Science

Lecture 7 – Code Iteration

A Guide to Your Process

Scheduling

Learning Objectives

Practice

Supporting Information

Class Discussion

Today’s Plan

  • Choose Lab #8 “Bonus Content”
  • 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

Bonus Content

  • Lab #8 topic is your choice!


  • Some options include:
    • Biodiversity and ecological communities
    • Pairwise comparisons (i.e., what to do after ANOVA says ‘at least one group differs’)
    • Heatmaps


  • What 1-2 topic(s) seem interesting to you?
    • Feel free to propose topics that aren’t listed!

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 what 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 named “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 brace ({/}) 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 takes the square root of each number
    • Function is sqrt
  • The loop should print the result for each square root in the Console
    • Function is print


  • Answer:
for(j in 5:25){
  j_root <- sqrt(j)
  print(j_root)
}

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 with j as 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 Pratice

  • For the loop with i as the index:
    • 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))
}

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 Syntax

# 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...") }


  • 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

Multiple ifs

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


  • 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 tomorrow!
    • Presentations during Lab #7 (this week)!
    • 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 lab

(By midnight)

  • Muddiest Point #7
  • Submit Draft 2 of Function Tutorials
    • Remember to include both the revised .Rmd and your “revision response”
    • Check the rubric for more details

Due before lecture

(By midnight)

  • Homework #7