R – Iterate over items of Vector

To iterate over items of a vector in R programming, use R For Loop.

The syntax to iterate over each item item in vector x is

for (item in x) {
    //code
}

For every next iteration, we have access to next element inside the for loop block.

Examples

In the following program, we take a vector in x, and iterate over its items using for loop.

example.R

x <- c(5, 25, 125)
for (item in x) {
    print(item)
}

Output

[1] 5
[1] 25
[1] 125

Now, let us take a vector x with string values and iterate over the items.

example.R

x <- c("a", "e", "i", "o", "u")
for (item in x) {
    print(item)
}

Output

[1] "a"
[1] "e"
[1] "i"
[1] "o"
[1] "u"
ADVERTISEMENT

Conclusion

In this R Tutorial, we learned how to over items of a vector using for loop, with the help of examples.