Loop with Multiple Conditions in R (2 Examples) | while- & for-Loops

 

In this tutorial, I’ll show how to write and run loops with multiple conditions in the R programming language.

Table of contents:

Let’s dig in:

 

Example 1: Writing Loop with Multiple for-Statements

In Example 1, I’ll show how to write a for-loop containing multiple for-statements:

for(i in 1:5) {                           # Head of first for-loop
 
  for(j in 1:3) {                         # Head of second for-loop
 
    print(paste("i =", i, "; j =", j))    # Some output
  }
}
# [1] "i = 1 ; j = 1"
# [1] "i = 1 ; j = 2"
# [1] "i = 1 ; j = 3"
# [1] "i = 2 ; j = 1"
# [1] "i = 2 ; j = 2"
# [1] "i = 2 ; j = 3"
# [1] "i = 3 ; j = 1"
# [1] "i = 3 ; j = 2"
# [1] "i = 3 ; j = 3"
# [1] "i = 4 ; j = 1"
# [1] "i = 4 ; j = 2"
# [1] "i = 4 ; j = 3"
# [1] "i = 5 ; j = 1"
# [1] "i = 5 ; j = 2"
# [1] "i = 5 ; j = 3"

Note that these kinds of loops are also called nested loops. You can learn more about that in this R programming tutorial.

 

Example 2: Writing Loop with Multiple if-Conditions

It is also possible to include several if (or else) conditions inside of a loop. Have a look at the following example code:

for(i in 1:5) {                           # Head of for-loop
 
  if(i < 4) {                             # First if-condition
 
    if(i %in% seq(2, 10, 2)) {            # Second if-condition
 
      print(i)                            # Some output
    }
  }
}
# [1] 2

In the previous R code we nested two if-conditions. However, we may also specify multiple logical conditions within a single if-statement:

for(i in 1:5) {                           # Head of for-loop
 
  if(i < 4 & i %in% seq(2, 10, 2)) {      # Combine two if-conditions
 
    print(i)                              # Some output
  }
}
# [1] 2

The output is the same.

Note that we could apply the same logic within other types of loops such as repeat-loops or while-loops.

 

Video, Further Resources & Summary

Would you like to know more about loops? Then you may watch the following video of my YouTube channel. I’m explaining the R programming code of this article in the video.

 

The YouTube video will be added soon.

 

Additionally, you might read the other tutorials of my website. I have published numerous articles about different types of loops already:

 

On this page, I illustrated how to write loops with multiple conditions in R programming. If you have additional questions, don’t hesitate to let me know in the comments below. Furthermore, please subscribe to my email newsletter to receive regular updates on the newest articles.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

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

Fill out this field
Fill out this field
Please enter a valid email address.

Top