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:
while (condition is true) {
statement;
}
Let us see an example to implement while loop in R:
marks <- 95
# while loop
while (marks < 100) {
print(marks)
marks = marks + 1
}
Output
[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:
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:
# Vectors
marks <- c(97, 90, 94, 95, 92)
# for loop
for (i in marks) {
print(i)
}
Output
[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:
# list
students <- list("amit", "john", "david", "rohit", "virat")
# for loop
for (x in students) {
print(x)
}
Output
[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