Control Flow

Use Cases & Syntax

Used to test if a specific case is true or false

Short-circuit evaluation:

  • Test if all conditions are true

  • Test if any conditions are true

  • Test if a condition is not true

Conditional evaluation

  • If statement: run code if this statement is true

    • Only used at the beginning of a conditional statement

  • Else if statement: if previous statements aren't true, try this

    • Can be used an unlimited number of times in an if statement

  • Else statement: catch-all for anything outside of prior statements

    • Only used to end a conditional statement

Inputs:

#If statement
a <- 2
b <- 1
if (a > b){
print("a is greater than b")}

#Else if statement
x <- 10
y <- 10
if (x > y){
print("x is greater than y")
} else if (x <= y){
print("x is less than or equal to y")
}

#Else statement
d <- 3
if (d > 5){
print("d is greater than 5")
} else if (d == 5){
print("d is equal to 5")
} else {
print("d is less than or equal to 5")
}

Outputs:

#If statement
[1] "a is greater than b"

#Else if statement
[1] "x is less than or equal to y"

#Else statement
[1] "d is less than or equal to 5"

Loops

Repeats a block of code a specified number of times or until some condition is met

  • While loop

  • For loop

  • Use break to terminate loop

Inputs:

#While loop
i <- 1
while (i < 5){
print(i)
i <- i + 1
}

#While loop with break
j <- 1
while (j < 5){
print(j)
j <- j + 1
if (j == 4){
break
}}

#For loop
fruit <- list("apple", "banana", "peach")
for (x in fruit) {
  print(x)
}

#Nested for loop
adjectives <- list("scrumptious", "overripe", "delicious")
fruit <- list("apple", "banana", "peach")
for (x in adjectives) {
    for (y in fruit) {
      print(paste(x, y))
}}

Outputs:

#While loop
[1] 1
[1] 2
[1] 3
[1] 4

#While loop with break
[1] 1
[1] 2
[1] 3

#For loop
[1] "apple"
[1] "banana"
[1] "peach"

#Nested for loop
[1] "scrumptious apple"
[1] "scrumptious banana"
[1] "scrumptious peach"
[1] "overripe apple"
[1] "overripe banana"
[1] "overripe peach"
[1] "delicious apple"
[1] "delicious banana"
[1] "delicious peach"

Comparison Operators

Operator
Description

>

Greater than

<

Less than

>=

Greater than or equal

<=

Less than or equal

==

Exactly equal

!=

Not equal to

&

Entry wise and

Input:

# Demonstrate comparison operators

# Assign values to variables
c1 <- 25
c2 <- 50
c3 <- 75
c4 <- 50

# Testing equality
c1 == c3
c2 == c4

# Changing values using assignment operators
c1 <- c1 * 3  # shorthand for c1 = c1 * 3
c4 <- c4 + 1  # shorthand for c4 = c4 + 1

# Testing less than and greater than
c1 < c2
c4 <= c2
c1 > c2
c3 >= c2

Output:

# Testing equality
# c1 == c3
[1] FALSE
# c2 == c4
[1] TRUE

# Testing less than and greater than
# c1 < c2
[1] FALSE
# c4 <= c2
[1] FALSE
# c1 > c2
[1] TRUE
# c3 >= c2
[1] TRUE

Resources

Last updated