For Loops

Example 1

# Example 1: Looping over values
students <- c("Kai", "Ana", "John", "Ella", "Belle")

for (name in students) {
  print(glue("{name} has {nchar(name)} letters."))
}

Example 2

# Example 2: Looping over row numbers
nrow(storms)
for (row in 2:nrow(storms)) {
  if (storms$lat[row] > storms$lat[row-1]) {
    print(glue("{storms$name[row]} is moving north."))
  } else if (storms$lat[row] < storms$lat[row-1]) {
    print(glue("{storms$name[row]} is moving south."))
  }
}

Challenge

When one storm ends and the next begins, the code compares the last row of one storm with the first row of the next. Change the loop so it skips the row comparison when a new storm starts.

Technique: Converting data formats, Cleaning data
Tools: R
Data Format: Statistics


First created: October 15, 2026
Last updated: October 20, 2026

Tutorial maintained by Nadia Muhe.

Tutorial created by Nadia Muhe.

Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International icon