Control Structures#

This lesson will cover how R code uses loops and conditionals, just like Python.

Conditions#

R uses a model similar to Python for control structures. The if and else if statements require a logical test that results in TRUE or FALSE, while else acts as a catch-all with no condition.

In terms of syntax, the main differences between R and Python are:

  • Conditions are enclosed in parentheses.

  • There is no : after the condition statement to indicate the code block to execute.

  • The code block to run is enclosed in {}, rather than being indicated by indentation.

  • elif in Python is called else if in R.

On the other hand, comparison operators in R are the following:

Operator

Name

Example

==

Equals

x == y

!=

Not equals

y != x

>

Greater than

x > y

<

Less than

y < x

>=

Greater than or equal to

x >= y

<=

Less than or equal to

y <= x

Let’s have a look at different examples:

x <- 14
y <- 120

if (y > x) {
  print("y is greater than x")
}
[1] "y is greater than x"
x <- 33
y <- 33

if (y > x) {
  print("y is greater than x")
} else if (x == y) {
  print("x and y are equal")
}
[1] "x and y are equal"
x <- 120
y <- 44

if (y > x) {
  print("y is greater than x")
} else if (x == y) {
  print("x and y are equal")
} else {
  print("x is greater than y")
}
[1] "x is greater than y"

R provides an ifelse function, which is very useful for converting data into boolean values.

# input vector
x <- c(12, 9, 23, 14, 20, 1, 5)

# ifelse() function to determine odd/even numbers
ifelse(x %% 2 == 0, "EVEN", "ODD")
  1. 'EVEN'
  2. 'ODD'
  3. 'ODD'
  4. 'EVEN'
  5. 'EVEN'
  6. 'ODD'
  7. 'ODD'

Loops#

while loops#

The syntax for while loops in R is the following:

while ( CONDITION ) {
STATEMENT1
STATEMENT2
ETC
}
x <- 0
while ( x < 100 ) {
    x <- x + 17 # Indentation is not required; it’s used here only to improve readability.
    print( x )
}
print("I exited the loop, yeah!")
[1] 17
[1] 34
[1] 51
[1] 68
[1] 85
[1] 102
[1] "I exited the loop, yeah!"

break - exit the loop#

As in Python, it stops the loop entirely.

# BREAK

i <- 1
while (i < 9) {
  print(i)
  i <- i + 1
  if (i == 5) {
    print("I'm all done!")
    break
  }
}
[1] 1
[1] 2
[1] 3
[1] 4
[1] "I'm all done!"

next - stop the current iteration#

It skips an interation of the loop and moves on to the next step in logic. In Python this corresponds to the continue keyword.

# NEXT
i <- 0
while (i < 8) {
  i <- i + 1
  if (i == 5) {
    print("Here is where I pass")
    next
  }
  print(i)
}
[1] 1
[1] 2
[1] 3
[1] 4
[1] "Here is where I pass"
[1] 6
[1] 7
[1] 8

for loops#

The syntax for for loops in R is the following:

for ( VAR in iterable ) {
STATEMENT1
STATEMENT2
ETC
}

In R, an iterable can be a numeric count or range (using : or seq), a series of elements in a list or vector, or a numeric range/limit applied to a vector.

# loops 10x, counting 1-10.
for(ii in 1:10) {
  print(ii)
}
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10
# loops once for each item in a vector
x <- c("a", "b", "x", "y", "z")
for(ii in x) {
  print(ii)
}
[1] "a"
[1] "b"
[1] "x"
[1] "y"
[1] "z"
# loops in a range of items (3x) mapped against a vector.
# therefore loops 3x total against a, b, and x.

x <- c("a", "b", "x", "y", "z")

for(ii in 1:3) {
  print(x[ii])
}
[1] "a"
[1] "b"
[1] "x"
# What about iterating across a range, but only at certain intervals?
# Use a sequence from 1-30 but count in intervals of 3

for(i in seq(1, 30, 3)) {
  print(ii)
}
[1] 3
[1] 3
[1] 3
[1] 3
[1] 3
[1] 3
[1] 3
[1] 3
[1] 3
[1] 3

seq_along()#

This function has a similar purpose to Python’s enumerate: it generates an integer sequence based on the length of an object.

x <- c("a", "b", "x", "y", "z")

for(ii in seq_along(x)) {
  print(ii)     # the integer of the vector item index
  print(x[ii])  # the actual value of the vector item
}
[1] 1
[1] "a"
[1] 2
[1] "b"
[1] 3
[1] "x"
[1] 4
[1] "y"
[1] 5
[1] "z"
# compare to this for-loop that skips integer/indexing and simply takes each value of the vector in sequence
for(letter in x) {
  print(letter)
}
[1] "a"
[1] "b"
[1] "x"
[1] "y"
[1] "z"

Practice exercises#

Exercise 55

1- Write a piece of code that prints “x is an even number” if a variable x (which you define) is even; otherwise, print “x is an odd number.” Test your code by setting x to both an odd and an even number. (Hint: You may find the modulus operator helpful here.)

Extra challenge: Can you modify the message to include the actual value of x in the output?

# Your answers here

Exercise 56

2- Create a variable named x and assign it an initial value. Then, create a loop that iterates over a range from 1 to 10. In each iteration, update the value of x by adding the current number in the loop to x.

# Your answers here

Exercise 57

3- Write a piece of code that calculates the sum of all integers from 0 up to a specified number. Use a while loop to calculate the sum. Then, test your result by comparing it with the output of the sum function applied to a sequence from 1 to the specified number.

# Your answers here