In this tutorial, we will learn about for loops in R. We will cover the basics of iterative execution using for loops.
A for loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The loop is typically used when the number of iterations is known before entering the loop.
The syntax for the for loop in R is:
for (item in iterable) {
# Code block to be executed
}
The for loop iterates over each item in the iterable object (such as a vector, list, or data frame) and executes the code block for each item.
for (i in 1:10) {
cat(i, " ", sep = "")
}
1 2 3 4 5 6 7 8 9 10
n <- 5
factorial <- 1
for (i in 1:n) {
factorial <- factorial * i
}
cat("Factorial of", n, "is", factorial)
Factorial of 5 is 120
arr <- c(1, 2, 3, 4, 5)
sum <- 0
for (num in arr) {
sum <- sum + num
}
cat("Sum of the elements in the vector is", sum)
Sum of the elements in the vector is 15