09 Feb R Loops
R loops execute a block of code and this code executes while the condition is true. Here are the types of loops in R:
- while loop
- for loop
while loop
In the while loop, the block of code executes only when the condition is true. It executes as long as the condition is true.
Here is the syntax:
1 2 3 4 5 |
while (condition is true) { statement; } |
Let us see an example to implement while loop in R:
1 2 3 4 5 6 7 8 9 |
marks <- 95 # while loop while (marks < 100) { print(marks) marks = marks + 1 } |
Output
1 2 3 4 5 6 7 |
[1] 95 [1] 96 [1] 97 [1] 98 [1] 99 |
for loop
The for loop is used when you can set how many times a statement is to be executed.
Here is the syntax:
1 2 3 4 5 |
for (value in k) { statements } |
Above, k can be a vector, list, etc.
Let us see an example to implement for loop in R. We will display a Vector:
1 2 3 4 5 6 7 8 9 |
# Vectors marks <- c(97, 90, 94, 95, 92) # for loop for (i in marks) { print(i) } |
Output
1 2 3 4 5 6 7 |
[1] 97 [1] 90 [1] 94 [1] 95 [1] 92 |
Let us see another example to implement for loop in R. We will display a List:
1 2 3 4 5 6 7 8 9 |
# list students <- list("amit", "john", "david", "rohit", "virat") # for loop for (x in students) { print(x) } |
Output
1 2 3 4 5 6 7 |
[1] "amit" [1] "john" [1] "david" [1] "rohit" [1] "virat" |
If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.
Read More:
No Comments