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] 10This 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
EasyYou will receive two lines of input:
- A comma-separated list of numbers (e.g.,
12,5,18,3,25,8,14) - A threshold value (e.g.,
10)
Using a for loop to iterate over the vector elements:
- Create a vector from the comma-separated numbers
- Loop through each element in the vector
- 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
10The output should be:
[1] 15
[1] 22
[1] 19
[1] 11Explanation: 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()This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators (AND, OR)Logical Operators Part 2 (NOT)Recap - Simple LogicVectorized Logic Part 1Vectorized Logic Part 22Variables and Data Types
Numeric Data TypeInteger Data TypeCharacter Data TypeLogical Data TypeChecking Data TypesNaming ConventionsMissing Values: NARecap - Variable Creation8Loops
For LoopWhile LoopBreakNext (Continue)Recap - FactorialSequence Generation (seq, :)Nested LoopsRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsInteger Division and ModuloAssignment OperatorsRecap - Simple MathComparison Operators6Basic IO
Print OutputCat for OutputOutput With VariablesReading Input with readline()Type Conversion BasicsRecap - Age CalculatorRecap - True or False9Functions
Declaring a FunctionFunction ArgumentsReturn ValuesRecap - Sigma FunctionRecap - Validation FunctionDefault Parameter Values12Iterating Over Sequences
Iterating Over Vector ElementsUsing seq_along()Iterating Characters (strsplitString Manipulation Functions