Control Statements in R Programming
Control statements are expressions used to control the execution
and flow of the program based on the conditions provided in the
statements. These structures are used to make a decision after
assessing the variable. In this article, we’ll discuss all the control
statements with the examples.
In R programming, there are 8 types of control statements as
follows:
if condition
if-else condition
for loop
nested loops
while loop
repeat and break statement
return statement
next statement
if condition
This control structure checks the expression provided in
parenthesis is true or not. If true, the execution of the statements
in braces {} continues.
Syntax:
if(expression){
statements
....
....
}
Example:
x <- 100
if(x > 10){
print(paste(x, "is greater than 10"))
}
Output:
[1] "100 is greater than 10"
if-else condition
It is similar to if condition but when the test expression in if
condition fails, then statements in else condition are executed.
Syntax:
if(expression){
statements
....
....
}
else{
statements
....
....
}
Example:
x <- 5
# Check value is less than or greater than 10
if(x > 10){
print(paste(x, "is greater than 10"))
}else{
print(paste(x, "is less than 10"))
}
Output:
[1] "5 is less than 10"
for loop
It is a type of loop or sequence of statements executed repeatedly
until exit condition is reached.
Syntax:
for(value in vector){
statements
....
....
}