To iterate over a vector in R, you can use a for
loop to access each element of the vector one by one.
In this example,
vec
with a series of numeric values.for
loop to iterate over each element of the vector. The loop variable item
will take on the value of each element in the vector, one at a time.print
function to print the current value of the loop variable item
.print
function sends the value of item
to the console, allowing us to see each element of the vector as it is processed.vec <- c(10, 20, 30, 40, 50)
for (item in vec) {
print(item)
}
[1] 10 [1] 20 [1] 30 [1] 40 [1] 50
In this example,
char_vec
with a series of string values.for
loop to iterate over each element of the vector. The loop variable item
will take on the value of each element in the vector, one at a time.print
function to print the current value of the loop variable item
.print
function sends the value of item
to the console, allowing us to see each element of the vector as it is processed.char_vec <- c("apple", "banana", "cherry", "date", "elderberry")
for (item in char_vec) {
print(item)
}
[1] "apple" [1] "banana" [1] "cherry" [1] "date" [1] "elderberry"
In this tutorial, we learned How to Iterate Over a Vector in R language with well detailed examples.