Menu
Coddy logo textTech

Iterating Over Vector Elements

Part of the Fundamentals section of Coddy's R journey — lesson 63 of 78.

While R's vectorized operations are powerful, sometimes you need to process each element individually with custom logic. A for loop lets you iterate through vector elements one at a time.

The simplest way to loop through a vector is to iterate directly over its elements:

fruits <- c("apple", "banana", "cherry")
for (fruit in fruits) {
  print(fruit)
}

Output:

[1] "apple"
[1] "banana"
[1] "cherry"

In each iteration, the loop variable fruit takes on the value of the next element in the vector. This approach is clean and readable when you only need the values themselves.

You can combine iteration with conditional logic to process elements selectively:

numbers <- c(3, 8, 2, 10, 5)
for (num in numbers) {
  if (num > 5) {
    print(num)
  }
}

Output:

[1] 8
[1] 10

This pattern is useful when you need to apply different operations based on each element's value, something that vectorized operations alone can't always handle.

challenge icon

Challenge

Easy

You will receive two lines of input:

  1. A comma-separated list of numbers (e.g., 12,5,18,3,25,8,14)
  2. A threshold value (e.g., 10)

Using a for loop to iterate over the vector elements:

  1. Create a vector from the comma-separated numbers
  2. Loop through each element in the vector
  3. For each element that is greater than or equal to the threshold, print that element using print()

For example, if the inputs are:

4,15,8,22,6,19,11
10

The output should be:

[1] 15
[1] 22
[1] 19
[1] 11

Explanation: The loop checks each element against the threshold (10). Elements 15, 22, 19, and 11 are all greater than or equal to 10, so they are printed. Elements 4, 8, and 6 are skipped.

Cheat sheet

A for loop allows you to iterate through vector elements one at a time and apply custom logic to each element.

Basic syntax for looping through a vector:

fruits <- c("apple", "banana", "cherry")
for (fruit in fruits) {
  print(fruit)
}

In each iteration, the loop variable takes on the value of the next element in the vector.

Combining loops with conditional logic to process elements selectively:

numbers <- c(3, 8, 2, 10, 5)
for (num in numbers) {
  if (num > 5) {
    print(num)
  }
}

This pattern is useful when you need to apply different operations based on each element's value.

Try it yourself

# Read input
con <- file("stdin", "r")
numbers_input <- suppressWarnings(readLines(con, n = 1))
threshold <- as.numeric(suppressWarnings(readLines(con, n = 1)))
close(con)

# Convert comma-separated string to numeric vector
numbers <- as.numeric(unlist(strsplit(numbers_input, ",")))

# TODO: Write your code below
# Use a for loop to iterate through the numbers vector
# For each element >= threshold, print it using print()
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals