for loop in R Programming Language
Table of Content:
Loops are used in programming to repeat a specific block of code. In this article, you will learn to create a for loop in R programming.
A for loop is used to iterate over a vector in R programming.
Syntax of for loop
for (val in sequence)
{
statement
}
Here, sequence
is a vector and val
takes on each of its value during the loop. In each iteration, statement
is evaluated.
Flowchart of for loop
Example: for loop
Below is an example to count the number of even numbers in a vector.
x <- c(2,5,3,9,8,11,6)
count <- 0
for (val in x) {
if(val %% 2 == 0) count = count+1
}
print(count)
Output
[1] 3
In the above example, the loop iterates 7 times as the vector x
has 7 elements.
In each iteration, val
takes on the value of corresponding element of x
.
We have used a counter to count the number of even numbers in x
. We can see that x
contains 3 even numbers.
Useful example of for loop
Code
# Nice example for(i in 1:10) { print(i) } print(1:10) fruits <- c("apple", "Banana", "Pomegranate") fruitLength <- rep(NA, length(fruits)) fruitLength names(fruitLength) <- fruits fruitLength for(a in fruits){ fruitLength[a] <- nchar(a) } fruitLength # another way to do the above thing fruitLength2 <- nchar(fruits) fruitLength2 names(fruitLength2) <- fruits fruitLength2 identical(fruitLength, fruitLength2)
Output
> for(i in 1:10) + { + + print(i) + } [1] 1 [1] 2 [1] 3 [1] 4 [1] 5 [1] 6 [1] 7 [1] 8 [1] 9 [1] 10 > print(1:10) [1] 1 2 3 4 5 6 7 8 9 10 > fruits <- c("apple", "Banana", "Pomegranate") > fruitLength <- rep(NA, length(fruits)) > fruitLength [1] NA NA NA > names(fruitLength) <- fruits > fruitLength apple Banana Pomegranate NA NA NA > for(a in fruits){ + fruitLength[a] <- nchar(a) + } > fruitLength apple Banana Pomegranate 5 6 11 > fruitLength2 <- nchar(fruits) > fruitLength2 [1] 5 6 11 > names(fruitLength2) <- fruits > fruitLength2 apple Banana Pomegranate 5 6 11 > identical(fruitLength, fruitLength2) [1] TRUE