R Basics – Conditional Statement and Loops

In the previous part of the R basics course, we learned about data storage options. Now let’s turn to working in R, that is, writing conditional statements and loops in this language.

Conditional statement

The general structure of a conditional statement in R is as follows:

The best way to illustrate how a conditional statement works is to use an example. Let’s first create a variable x that is to contain a value:

Now we will write a simple conditional statement that will output the information whether the variable x is a positive number:

By executing the line of code entered, we get:

Let’s add an if else statement to the if statement, which, if the variable x is negative, will show us other information:

Let’s execute the statement we entered:

Let’s change the value of the variable x to negative:

Let’s execute the statement again:

If the variable x takes the value 0, we should see a different message than in the two examples above. We can add an additional if else to our statement.

Let’s change x to zero:

And let’s execute the statement:


The general structure of a for loop in R is as follows:

This is what it looks like in practice. Let’s create a vector x with five numbers:

We display the vector x:

Let’s write a loop that counts the power of each value in the vector x and displays the results of this action:

Let’s execute the loop:

The for loop is executed for each element of the vector x.


The general structure of a for while in R is as follows:

The loop is executed until the check is true. We will show this using the variable y equal to 0. Let’s write a while loop that displays the result of an action on the variable y. The action will add two to it in the loop until its value is less than 16. The code will look like this:

Let’s execute the loop:

Break i next

The for and while loops can also be broken using break and next. Break is used to stop the loop while next is used to go to the next element. Let’s use the break stop in the previous while loop when y is equal to 8:

Let’s execute the modified loop:

The loop was stopped when y was equal to 8. Now let’s skip this result in the while loop:

Let’s run the modified loop:

Loops and conditional statements can intertwine to form complex code structures.

The for loop is used in automatic processing of large collections, such as grids. We first code the action on a single file, that is, loading the file, processing it, and saving the result. This action is then closed in a for loop that executes it on our set of files.

In the next course, “R Basics”, we will introduce how to code your own functions.

Leave a Reply

Your email address will not be published.

Translate using Google Translate»
Social media & sharing icons powered by UltimatelySocial

Podoba Ci się nasza strona? Odwiedź nasz profil