To iterate over a vector with index in R, you can use a for loop along with the seq_along function or the seq_len function.
In this example,
num_vec
with several numeric values.for
loop to iterate over the indices of the vector. We achieve this by using the seq_along
function, which generates a sequence from 1 to the length of the vector.print
function. This helps us see the index-value pairs as the loop iterates through the vector.i
, and the corresponding value from num_vec
is accessed using num_vec[i]
.num_vec <- c(10, 20, 30, 40, 50)
for (i in seq_along(num_vec)) {
cat("Index:", i, "Value:", num_vec[i], "\n")
}
Index: 1 Value: 10 Index: 2 Value: 20 Index: 3 Value: 30 Index: 4 Value: 40 Index: 5 Value: 50
In this example,
char_vec
with several string values.for
loop to iterate over the indices of the vector. The seq_len
function is used here to generate a sequence from 1 to the length of the vector, similar to seq_along
.print
function. This helps us observe the index-value pairs for the character vector.i
, and the corresponding value from char_vec
is accessed using char_vec[i]
.char_vec <- c("apple", "banana", "cherry", "date")
for (i in seq_len(length(char_vec))) {
cat("Index:", i, "Value:", char_vec[i], "\n")
}
Index: 1 Value: apple Index: 2 Value: banana Index: 3 Value: cherry Index: 4 Value: date
In this tutorial, we learned How to Iterate Over a Vector with Index in R language with well detailed examples.