...

Artificial Intelligence - R Programming Basic

Back to Course

Lesson Description


Lession - #812 Loops in R



Loops in R Programming

Loops are used to repeateadly execute some expressions or statements inside loop body, by iterateing vector,array. The keywords for loops in R, are same as in other programming languages, and used like an iterator method as found in other object-orientated programming languages.
.

SNO LOOP DESCRIPTION EXAMPLE
1 FOR for loop can be used to execute a set of statements or expressions once for each item in a vector, array, list, etc. The syntax of for loop is as follows
for (value in vector>
{
statements
}
#Create Ocean vector
ocean <- c('Atlantic','Pacific','Indian','Artic'>

for(i in ocean>

print(i>

Output:

[1] "Atlantic"
[1] "Pacific"
[1] "Indian"
[1] "Artic"
2 WHILE While loop is used to repeat a statement or block of code until the condition is false. Here the condition is checked before the code inside the body of the loop.The syntax is as follows:
while (test_expression>
{
statement
}
x <- c("Welcome","to","Techedhub">

cnt <- 1
while (cnt < 5>
{
print(x>

cnt = cnt + 1
}

Output:

[[1] "Welcome" "to" "Techedhub"
[1] "Welcome" "to" "Techedhub"
[1] "Welcome" "to" "Techedhub"
[1] "Welcome" "to" "Techedhub"
3 REPEAT It is a special type of loop in R, where there is no condition to exit from, a break statement with a user-defined condition is used to exit from the loop. Due to this unique property of the loop makes it special from the other type of loops. The syntax is as follows:
repeat {
commands
if(condition>
{
break
}
}
x <- c("Hello","World">

cnt <- 2
repeat {
print(x>

cnt <- cnt+1
if(cnt > 5>
{
break
}
}

Output:

[1] "Hello" "World"
[1] "Hello" "World"
[1] "Hello" "World"
[1] "Hello" "World"