R Programming looping statement
R loops
There may be a situation when you need to execute a block of
code several number of times. In general, statements are executed sequentially.
The first statement in a function is executed first, followed by the second,
and so on.
Programming languages provide various control structures
that allow for more complicated execution paths.
A loop statement allows us to execute a statement or group
of statements multiple times and the following is the general form of a loop
statement in most of the programming languages −
R programming language provides the following kinds of loop
to handle looping requirements.
The Repeat loop executes the same
code again and again until a stop condition is met.
Syntax
The basic syntax for creating a repeat loop in R is −
repeat { commands if(condition) { break }}
Example
v <- c("Hello","loop")
cnt <- 2
repeat {
print(v)
cnt <- cnt+1
if(cnt > 5) {
break
}
}
The While loop executes the same code again and again
until a stop condition is met.
Syntax
The basic syntax for creating a while loop in R is −
while (test_expression) { statement}
Here key point of the while loop is
that the loop might not ever run. When the condition is tested and the result
is false, the loop body will be skipped and the first statement after the while
loop will be executed.
Example
v <- c("Hello","while loop")
cnt <- 2
while (cnt < 7) {
print(v)
cnt = cnt + 1
}
A For loop is a repetition control
structure that allows you to efficiently write a loop that needs to execute a
specific number of times.
Syntax
The basic syntax for creating a for loop statement in R
is −
for (value in vector) { statements}
R’s for loops are particularly flexible in that they
are not limited to integers, or even numbers in the input. We can pass
character vectors, logical vectors, lists or expressions.
Example
v <- LETTERS[1:4]
for ( i in v) {
print(i)
}
Comments
Post a Comment