In this tutorial, we will learn about different types of loops in R. We will cover the basics of for, while, and repeat loops.
A loop is a control flow statement that allows code to be executed repeatedly based on a condition.
R supports three types of loops: for loops, while loops, and repeat loops.
A for loop is used when the number of iterations is known before entering the loop. The syntax for the for loop is:
for (variable in sequence) {
# Code block to be executed
}
A while loop is used when the number of iterations is not known beforehand. The syntax for the while loop is:
while (condition) {
# Code block to be executed
}
A repeat loop is used to execute a code block repeatedly until a condition is met. The syntax for the repeat loop is:
repeat {
# Code block to be executed
if (condition) {
break
}
}
for (i in 1:10) {
cat(i, ' ')
}
1 2 3 4 5 6 7 8 9 10
i
and initialize it to 1.i <- 1
while (i <= 5) {
cat(i, ' ')
i <- i + 1
}
1 2 3 4 5
i
and initialize it to 1.i <- 1
repeat {
cat(i, ' ')
i <- i + 1
if (i > 3) {
break
}
}
1 2 3