Using seq_along()
Part of the Fundamentals section of Coddy's R journey — lesson 64 of 78.
Sometimes you need both the element's value and its position in the vector. While iterating directly over elements is clean, it doesn't give you access to the index. The seq_along() function solves this by generating a sequence of indices for any vector.
The seq_along() function returns a sequence from 1 to the length of the vector:
fruits <- c("apple", "banana", "cherry")
print(seq_along(fruits))Output:
[1] 1 2 3By looping over these indices, you can access both the position and the value:
fruits <- c("apple", "banana", "cherry")
for (i in seq_along(fruits)) {
cat(i, ":", fruits[i], "\n")
}Output:
1 : apple
2 : banana
3 : cherryThis approach is especially useful when you need to modify elements at specific positions or compare elements with their neighbors. Using seq_along() is safer than 1:length(vec) because it handles empty vectors correctly, returning an empty sequence instead of 1:0.
Challenge
EasyYou will receive a single line of input containing comma-separated numbers (e.g., 10,20,30,40,50).
Using seq_along() to iterate over the vector with indices:
- Create a vector from the comma-separated input
- Loop through the vector using
seq_along()to get both the index and value - For each element, print the index, the value, and the cumulative sum up to that point (sum of all elements from position 1 to the current position)
Use cat() with the format: Position X: VALUE (Running total: TOTAL) followed by a newline.
For example, if the input is:
5,10,15,20The output should be:
Position 1: 5 (Running total: 5)
Position 2: 10 (Running total: 15)
Position 3: 15 (Running total: 30)
Position 4: 20 (Running total: 50)Explanation: At position 1, the value is 5 and the running total is 5. At position 2, the value is 10 and the running total is 5+10=15. At position 3, the value is 15 and the running total is 5+10+15=30, and so on.
Hint: Use sum(vector[1:i]) to calculate the cumulative sum up to position i.
Cheat sheet
The seq_along() function generates a sequence of indices from 1 to the length of a vector:
fruits <- c("apple", "banana", "cherry")
print(seq_along(fruits))
# Output: [1] 1 2 3Use seq_along() in a loop to access both the index and value:
fruits <- c("apple", "banana", "cherry")
for (i in seq_along(fruits)) {
cat(i, ":", fruits[i], "\n")
}
# Output:
# 1 : apple
# 2 : banana
# 3 : cherryUsing seq_along() is safer than 1:length(vec) because it handles empty vectors correctly, returning an empty sequence instead of 1:0.
Try it yourself
# Read input
con <- file("stdin", "r")
input_line <- suppressWarnings(readLines(con, n = 1))
close(con)
# Convert comma-separated string to numeric vector
numbers <- as.numeric(strsplit(input_line, ",")[[1]])
# TODO: Write your code below
# Use seq_along() to loop through the vector
# For each position, print the index, value, and running total
# Use cat() with format: Position X: VALUE (Running total: TOTAL)\nThis 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