Control Structures in R Programming with Examples   Recently updated !


1. Objective

In this R tutorial, we are going to discuss the Control Structures in R programming. There are 8 control statements in R such as if, if-else, for, while, next, repeat, break etc. We will cover all R Control Statements with their syntax and examples in this R programming tutorial.

Control Structures in R Programming

2. What are Control Structures in R Programming?

R has the standard control structures we would expect. expr can be multiple statements by enclosing them in braces { }. It is more efficient to use built-in functions rather than control structures whenever possible. These allow us to control the flow of execution of a script typically inside of a function.

Control structures define the flow of the program. The decision is been based on the evaluation of a variable.

There are eight control Structures in R listed below:

  • if
  • if-else
  • for
  • nested loops
  • while
  • repeat and break
  • next
  • return

3. List of R Control Structures with Examples

Now we will discuss these Control Structures in R one by one in detail:

3.1. if

If this condition is true, then carry out a certain task. R makes it even easier: You can drop the word then and specify your choice in an if statement.

Syntax:

if (test_expression) {
statement
}

R if Statement Example:

x <- 1:15
if (sample(x, 1) <= 10) {
print("x is less than 10")

3.2. if-else

An if…else statement contains the same elements as an if statement (see the preceding section), and then some extra:

  • The keyword else, placed after the first code block
  • Second block of code, contained within braces, that has to be carried out if and only if the result of the condition in the if() statement is FALSE

Syntax:

if (test_expression) {
statement
} else {
statement
}

R if-else Statement Example:

x=10
x=10
if (x>1 & x<7) {
print("x is between 1 and 7")
} else if (x>8 & x< 15) {
print("x is between 8 and 15")
}

Output:

[1] "x is between 8 and 15"

3.3. for

A loop is a sequence of instructions that is repeated until a certain condition is been reached. for, while and repeat, with the additional clauses break and next are used to construct loops.

R for loop Example:

This loop structure, made of the rectangular box ‘init’, the diamond, and the rectangular box. It is executed a known number of times. for block is been contained within curly braces.

x = c(1,2,3,4,5)
for(i in 1:5) {
print(x[i])
}

Output:

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5

3.4. Nested loops

It is similar to the standard for loop, which makes it easy to convert for loop to a foreach loop. Unlike many parallel programming packages for R, foreach doesn’t require the body of for loop to be turned into a function. … We can call this the nesting operator because it is used to create nested foreach loops

R nested loop Example:

m <- matrix(1:10, 2)
for (i in seq(nrow(m))) {
    for (j in seq(ncol(m))) {
print(m[i, j])
}
}

3.5. while

The format is while(cond) expr, where cond is the condition to test and expr is an expression.

R would complain about the missing expression that was supposed to provide the required True or False and in fact, it does not know ‘response’ before using it in the loop. We can also do this because, if we answer right at first attempt, the loop will not be executed at all.

R while loop Example:

x = 2.987
while(x <= 4.987) {
x = x + 0.987
print(c(x,x-2,x-1))
}

Output:

[1] 3.974 1.974 2.974
[1] 4.961 2.961 3.961
[1] 5.948 3.948 4.948

Be sure there is a way to exit out of a while loop.

3.6. repeat and break

We use break statement is used inside a loop (repeat, for, while) to stop the iterations and flow the control outside of the loop. While in a nested looping situation, where there is a loop inside another loop, this statement exits from the innermost loop that is being evaluated.

A repeat loop is used to iterate over a block of code multiple numbers of times. There is no condition check in repeat loop to exit the loop. We ourselves put a condition explicitly inside the body of the loop and use the break statement to exit the loop. Failing to do so will result in an infinite loop.

Syntax:

repeat {
# simulations; generate some value have an expectation if within some range,
# then exit the loop
if ((value - expectation) <= threshold) {
break
}
}

The repeat loop is an infinite loop and used in association with a break statement.

R repeat and break Statement Example:

Below, the code shows repeat statement in R:

[/php]a = 1
repeat {

print(a) a = a+1 if(a > 4) break

}[/php]

Output:

[1] 1
[1] 2
[1] 3
[1] 4

A break statement is used in a loop to stop the iterations and flow the control outside of the loop.

R break Statement Example:

Below the code shows break statement in R:

x = 1:10
for (i in x){
if (i == 2){
break
}
print(i)
}
[1] 1

3.7. next

next jumps to the next cycle without completing a particular iteration. In fact, it jumps to the evaluation of the condition holding the current loop. Next statement enables to skip the current iteration of a loop without terminating it.

R next Statement Example:

x = 1: 4
for (i in x) {
if (i == 2) {
next
}
print(i)
}

Output:

[1] 1
[1] 3
[1] 4

3.8. return

Many times, we will require functions to do some processing and return back the result. This is accomplished with the return() statement in R.

Syntax:

return(expression)

R return Statement Example:

check <- function(x) {
if (x > 0) {
result <- "Positive"
} else if (x < 0) {
result <- "Negative"
} else {
result <- "Zero"
}
return(result)
}

Here, are some sample runs.

> check(1)
[1] "Positive"
> check(-10)
[1] "Negative"
> check(0)
[1] "Zero"

4. Wrapping up the use of loops in R

  • Be careful when you use repeat:
  • Make sure that a termination is explicitly set by testing a condition or we can end up in an infinite loop.
  • It is better to use one or more function calls within the loop if a loop is getting (too) big.

5. Conclusion

Hence, Control Structures are the backbone of any programming language. As it changes the flow of the program. In this R tutorial, we have studied in detail about the control statements along with its syntax and uses, loop statements and how to operate this loops with different control structures. Hope you liked this blog, if you have any query in Control Structures in R, so feel free to share with us.

See Also-

Leave a comment

Your email address will not be published. Required fields are marked *