R – Loops

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 −

Loop Architecture

R For Loop

The R For Loop is used to repeat a block of statements until there are no items in the Vector. For loop is one of the most used loops in any programming language. Let us see the syntax of the For Loop in R:

The basic syntax of the For loop in R Programming language is

for (val in vector)  {
     Statement 1
     Statement 2
     ………
     Statement N
}

If you observe the above syntax of for loop in R, Vector may be string or integer, or anything you want to iterate.

  • R For loop starts with Object, means it will iterate Vector, and then it will assign the first item to value. For instance, our vector values are A: E means, it will assign A to val.
  • Next, it will execute the statements inside the R For loop.
  • After completing the statements, it will go to the vector and assign the next value to the val.
  • The process will be repeated until there are no items in the vector.

R For Loop Example

In this example, we are going to explain how to use for loop in R Programming to extract individual items or data from R Vector.

# For Loop Example

countries <- c('India', 'U K', 'Japan', 'U S A', 'Australia', 'China')

for (str in countries) {
  print(paste("Countries are:  ", str))
}
print("----This is Coming from Outside the For Loop---")

ANALYSIS

Firs,t we declared Countries Vector and assigned the following values.

countries <- c('India', 'U K', 'Japan', 'U S A', 'Australia', 'China')

In the next line, we used the R for loop to iterate through the Countries vector and display the individual vector items.

for (str in countries) {
  print(paste("Countries are:  ", str))
}

In the next line, we used a print statement outside the for loop. This statement will be executed once the compiler exit from the for loop in R.

print("----This is Coming from Outside the For Loop---")

OUTPUT

From the above Screenshot, you can observe that we used the Countries List for second for Loop in R example code.

countries <- c('India', 'U K', 'Japan', 'U S A', 'Australia', 'China')

First Iteration

  • For the first Iteration, Country = ‘India’.
  • It means there are some items in the vector, so it will execute the print statement inside the for loop.

Second Iteration

  • For the second Iteration of the R for loop, Country = ‘U K’.
  • It means there are some items in the vector, so it will execute the print inside the for loop.

Third Iteration

  • For the third Iteration, Country = ‘Japan’.
  • It means there are some items in the vector, so it executes the statement inside a for loop.

Fourth Iteration

  • For the fourth Iteration of for loop, Country = ‘U S A’.
  • It means there are some items in the vector, so it executes print statements inside a for loop.

Fifth Iteration

  • For the fifth Iteration, Country = ‘Australia’.
  • It means there are some items in the vector, so it executes the print statement inside the for loop.

Sixth Iteration

  • For the sixth Iteration, Country = ‘China’.
  • It means there are some items in the vector, so it will compile the print statement inside a for loop.

For the Seventh iteration, there are no items in the vector to assign for Country variable. So, it will exit from for loop.

For Loop Example 2

In this for loop in R example, we are going to explain the working functionality of the For Loop on integer vector.

# For Loop Example

numbers <- c(1:10)

for (num in numbers) {
  print(9 * num)
}
print("---- This is Coming from Outside the For Loop ---")

OUTPUT


R While Loop Syntax

The syntax of the While loop in R Programming language is

While ( Expression )  {
    statement 1
    statement 2
    ………….
    statement N;
    # Increment or Decrements the Values
}
#This statement is from Outside the While Loop

First, it will check for the expression inside the While loop. If the expression result is True, then the statement or group of statements under the while loop block will be executed. If the expression return is False, then it will come out of the loop and execute other statements outside the while loop.

While Loop in R Programming example

This program for a while loop in r allows the user to enter an integer value. Using this value, it adds those values up to 10.

# R While Loop Example

total = 0
number <- as.integer(readline(prompt="Please Enter any integer Value below 10:  "))

while (number <= 10)  {
  total = total + number
  number = number + 1
}

print(paste("The total Sum of Numbers From the While Loop is:  ", total))

OUTPUT: We are going to enter number = 6. It means, total = 6 + 7 + 8 + 9 + 10 = 40

ANALYSIS

Within the following statements of this r while loop, First, we declared the total variable and assigned it to Zero. Next, it will ask the user to enter any integer value below 10, and we are assigning the user entered value to a number variable.

total = 0
number <- as.integer(readline(prompt="Please Enter any integer Value below 10:  "))

Next line, we used the R While loop, and the expression inside the While loop will make sure that the given number is less than or equal to 10.

while (number <= 10)  {
  total = total + number
  number = number + 1
}

In this while loop in R example, the user Entered value: number = 6, and we initialized the total = 0.

First Iteration

total = total + number

total = 0 + 6 ==> 6

Next, the number will be incremented by 1 (number = number + 1). Please refer R Arithmetic Operators article to understand this + notation.

Second Iteration

Within the first Iteration of r while loop, the values of both number and total changed as number = 7 and total = 6

total = total + number

total = 6 + 7 ==> 13

Next, the number will be incremented by 1.

Third Iteration

Within the second Iteration, the values of both number and total have been changed as number = 8 and total = 13

total = total + number

total = 13 + 8 ==> 21

Next, the number incremented by 1.

Fourth Iteration

Within the third Iteration, the values of both number and total changed as number = 9 and total = 21

total = total + number

total = 21 + 9 ==> 30

Next, the number incremented by 1

Fifth Iteration

Within the fourth Iteration, the values of both number and total changed as number = 10 and total = 30

total = total + number

total = 30 + 10 ==> 40

Next, the number incremented by 1

Here Number = 11 so, the condition present inside the while loop (number <= 10) will fail

The last print statement will print the total sum of digits present in the given number as output.

print(paste("The total Sum of Numbers From the While Loop is:  ", total))

Infinite While Loop in R Programming

If you forgot to increment or decrements the value inside the while loop, then the R while loop executes infinite times (also called as infinite while loop).

# Infinite While Loop in R Programming Example

number <- 1

while (number < 10)  {
  print(paste("Number from the While Loop is:  ", number))
}

OUTPUT

ANALYSIS

Here, in this R while loop example, the number will always be 1, and the number is always less than 10, so while loop executes infinite times. Now, let us add + operator (number = number + 1) inside the while loop to the above example.

# Infinite While Loop in R Programming Example

number <- 1

while (number < 10)  {
  print(paste("Number from the While Loop is:  ", number))
  number = number + 1
}

Now, when it reaches 10, the condition (number < 10) will fail. Let us see the output of while loop example

OUTPUT


R Repeat loop Syntax

The syntax of the While loop in R Programming language is

repeat  {
    statement 1
    statement 2
    ………….
    statement N
    # Please provide Condition to exit or use Break Statement
}
#This statement is from Outside the Repeat Loop

First, it will execute the statements inside the loop, and if there are any loop breaking statements, then it will exit from the loop.

R Repeat Loop example

This program helps us to understand the Repeat in R Programming. It allows the user to enter an integer value below 10. Using this value, it adds those values up to 10.

# R Repeat Loop Example

total <- 0
number <- as.integer(readline(prompt="Please Enter any integer Value below 10:  "))

repeat  {
  total = total + number
  number = number + 1
  if (number > 10)  {
    break
  }
}

print(paste("The total Sum of Numbers From the Repeat Loop is:  ", total))

OUTPUT: We are going to enter number = 7. It means total = 7 + 8 + 9 + 10 = 34

ANALYSIS

Within the following statements, First, we declared the total variable and assigned it to Zero. Next, it will ask the user to enter any integer value below 10, and we are assigning the user entered value to a number variable.

total <- 0
number <- as.integer(readline(prompt="Please Enter any integer Value below 10:  "))

Next line, we used the While loop, and the expression inside the While loop will make sure that the given number is less than or equal to 10.

repeat  {
  total = total + number
  number = number + 1
}

In this R repeat example, User Entered value: number = 7 and we initialized the total = 0

First Iteration

  • total = total + number
  • total = 0 + 7 ==> 7

Next, number will be incremented by 1 (number = number + 1). Please refer R Arithmetic Operators article to understand this + notation.

Second Iteration

Within the first Iteration, the values of both the number and total changed as number = 8 and total = 7

  • total = total + number
  • total = 7 + 8 ==> 15

Next, number incremented by 1.

R Repeat Third Iteration

Within the second Iteration, the values of both the number and total changed as number = 9 and total = 15

  • total = total + number
  • total = 15 + 9 ==> 24

Next, number = number + 1

Fourth Iteration

Within the third Iteration, the values of both the number and total changed as number = 10 and total = 24

  • total = total + number
  • total = 24 + 10 ==> 34

Next, number = number + 1

Here, Number = 11, and the condition present inside the If Statement (number > 10) is True. So, the Break statement executed and it will exit from the loop

 if (number > 10)  {
    break
  }

The last print statement print the total sum of digits present in the given number as output.

print(paste("The total Sum of Numbers From the While Loop is:  ", total))

Infinite Repeat in R Programming

If you forgot to use the Conditions or Break statement to terminate the R Repeat loop, then statements inside the loop executed infinite times (also called as an infinite loop).

# Infinite Repeat R Loop Example

total <- 0
number <- as.integer(readline(prompt="Please Enter any integer Value:  "))

repeat  {
  total = total + number
  number = number + 1
  print(number)
}

OUTPUT

ANALYSIS

In this R repeat example, there is no condition to check or no break statement to break the loop, so repeat loop will go on executing the statements infinite times. Now, let us add the Break statement inside the If statement.

# R Repeat Loop Example

total <- 0
number <- as.integer(readline(prompt="Please Enter any integer Value below 10:  "))

repeat  {
  total = total + number
  number = number + 1
  if (number > 15)  {
    break
  }
  print(number)
}

Now, when it reaches 15, the condition will fail. Let us see the output

Follow Us On