The R programming language supports for, while and repeat loops, with the additional clauses break and next.
Example: For Loop in R
for(i in 1:5) {
print (i)
}
Output:
1
2
3
4
5
Example: For Loop to Print Odd Numbers Only
# print odd numbers
for (i in 1:10) {
if (!i %% 2){
next
}
print(i)
}
Output:
1
3
5
7
9
Example: While Loop in R
i <- 1
while (i < 5) {
print(i)
i = i+1
}
Output:
1
2
3
4