Control Flow in R

Week 7, Part 1

Jeff Jacobs

DSAN Summer Bootcamp 2024
Georgetown University

Control Flow

  • In case you haven’t heard this term…

  • Control flow is just the idea of: how do we control the flow of program execution (individual statements or blocks) in [programming language]

Code Blocks

Python uses Indentation →→

for i in range(5):
  print("Hello")
  print("Please run this code 5 times")
Hello
Please run this code 5 times
Hello
Please run this code 5 times
Hello
Please run this code 5 times
Hello
Please run this code 5 times
Hello
Please run this code 5 times

R uses curly braces {}

for (i in 1:5) {
  print("Hello")
  print("Please run this code 5 times")
}
[1] "Hello"
[1] "Please run this code 5 times"
[1] "Hello"
[1] "Please run this code 5 times"
[1] "Hello"
[1] "Please run this code 5 times"
[1] "Hello"
[1] "Please run this code 5 times"
[1] "Hello"
[1] "Please run this code 5 times"

Conditional Statements

If Statements

import datetime
cur_time = datetime.datetime.now()
print(f"The current time is {cur_time.hour}:{cur_time.minute}")
The current time is 17:32
if cur_time.hour < 12:
    print("Good morning!")
elif cur_time.hour < 18:
    print("Good afternoon!")
else:
    print("Good evening!")
Good afternoon!
library(lubridate)
cur_time <- Sys.time()
writeLines(paste0(
    "The current time is ",
    hour(cur_time),":",
    minute(cur_time)
))
The current time is 17:32
if (hour(cur_time) < 12) {
    print("Good morning!")
} else if (hour(cur_time) < 18) {
    print("Good afternoon!")
} else {
    print("Good evening!")
}
[1] "Good afternoon!"

(We’ll learn about lubridate soon!)

The Ternary Operator

"morning" if cur_time.hour < 12 else "evening"
'evening'
ifelse(
    hour(cur_time) < 12,
    "morning",
    "evening"
)
[1] "evening"

Loops

For Loops: The Software Engineer’s Bread and Butter

  • Many different ways to loop (find one that clicks for you!)
  • For loops often the “default” approach (because of C)
for i in range(1, 10):
    print(i)
1
2
3
4
5
6
7
8
9
for (i in 1:10) {
    print(i)
}
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10

Vectorized Operations: The Data Scientist’s Bread and Margarine

  • You’ve been hired as the lead data scientist for a food delivery service (congrats!)
  • You’re given data on (a) miles traveled and (b) hours driven, for each driver
  • Your goal: find the distribution of average speeds!
import pandas as pd
miles_data = [11, 52, 13]
hrs_data = [2, 3, 5]
driver_df = pd.DataFrame({
    'miles': miles_data,
    'hrs': hrs_data
})
print(driver_df.to_markdown())
miles hrs
0 11 2
1 52 3
2 13 5
miles_data <- c(11, 52, 13)
hrs_data <- c(2, 3, 5)
driver_df <- data.frame(
    miles=miles_data,
    hrs=hrs_data
)
driver_df
miles hrs
11 2
52 3
13 5

The Loop Approach

for (i in 1:nrow(driver_df)) {
  driver_df[i, 'mph'] <- driver_df[i, 'miles'] / driver_df[i, 'hrs']
}
driver_df
miles hrs mph
11 2 5.50000
52 3 17.33333
13 5 2.60000
  • It works! But CPUs have hyper-optimized linear algebra
  • \(\implies\) Operations on a length-1000 vector significantly faster than a loop performing an operation 1000 times

The Vectorized Approach 💯

driver_df['mph'] = driver_df['miles'] / driver_df['hrs']
print(driver_df.to_markdown())
miles hrs mph
0 11 2 5.5
1 52 3 17.3333
2 13 5 2.6
driver_df['mph'] = driver_df$miles / driver_df$hrs
driver_df
miles hrs mph
11 2 5.50000
52 3 17.33333
13 5 2.60000

Vectorizing Your Brain

  • Thinking in terms of vectors will be annoying at first! Many common algorithms are “naturally” described via loops…
  • It will pay off over the course of your career, I promise!
N <- 50000
set.seed(2024)
vec_start_time <- Sys.time()
big_vec1 <- rnorm(N, 0, 1)
big_vec2 <- rnorm(N, 0, 1)
product <- big_vec1 * big_vec2
vec_end_time <- Sys.time()
vec_end_time - vec_start_time
Time difference of 0.003620863 secs
loop_start_time <- Sys.time()
product <- c()
for (i in 1:N) {
  elt1 <- big_vec1[i]
  elt2 <- big_vec2[i]
  product <- c(product, elt1 * elt2)
}
loop_end_time <- Sys.time()
loop_end_time - loop_start_time
Time difference of 2.33628 secs
  • (For \(N = 100K\), 0.006 vs. 9.08 seconds!)

How is it That Much Faster?

  • The long answer: take DSAN 5500 😜 The short answer:
  • Simple math operations (addition, multiplication) are easily parallelized under the hood;
  • Sequential memory reads are significantly faster than non-sequential reads—vectors can be stored in contiguous “chunks” of memory that computer can rapidly scan over
    • (Think of how it’s easier to count people standing in a line than people scattered around a room!)

Functions

Anonymous Functions

  • In Python you declare the name of a function using def
  • In R, you make the function without a name, then assign it to a variable:
def multiply_by_5(num):
  return num * 5
multiply_by_5(10)
50
multiply_by_5 <- function(num) {
  return(num * 5)
}
multiply_by_5(10)
[1] 50
  • (Python also has anonymous functions, via lambda:)
double_it = lambda x: x * 2
double_it(10)
20

Variable Scope

  • Huge point (especially for Week 7 Assignment)!
  • Think of functions as “mini-programs”, where variables (including arguments) get created when the function starts and then destroyed when the function finishes. Compare:
val <- c(1, 2, 3)
print(val)
[1] 1 2 3
update_val <- function() {
  val <- val * 5
}
update_val()
print(val) # 😵
[1] 1 2 3
val <- c(1, 2, 3)
print(val)
[1] 1 2 3
compute_new_val <- function(orig_val) {
  return(orig_val * 5)
}
val <- compute_new_val(val)
print(val) # 😎
[1]  5 10 15

Positional vs. Keyword Arguments

  • Just like Python, R functions can accept two types of arguments…

Positional arguments are required (function call will produce error if any positional argument is missing)

div_by_2 <- function(num) {
  return(num / 2)
}
div_by_2(11)
[1] 5.5

Keyword arguments are optional

div_by_2 <- function(num, round=FALSE) {
  div_result <- num / 2
  final_result <- ifelse(round,
    round(div_result),
    div_result
  )
  return(final_result)
}
div_by_2(11, round=TRUE)
[1] 6

Applying Functions to Vectors

  • We’ve been “manually” calling functions, like func(arg)
  • What if we want to apply a function to a vector of elements? Ex: capitalize a big list of names
  • Base R provides a family of apply() functions: sapply() for vectors; lapply() for lists; apply() for matrices (requires specifying axis: columns or rows)
capitalize <- function(name) {
  return(tools::toTitleCase(name))
}
capitalize("jeff")
[1] "Jeff"
names <- c("ali", "boris", "chad")
sapply(names, capitalize)
    ali   boris    chad 
  "Ali" "Boris"  "Chad"