How To For Loop In R Programming Language? – POFTUT

How To For Loop In R Programming Language?

R is a programming language which is mainly used for statistical work. We can use for loops in R in different ways. We can use R for loop with the vector data type and in a regular way like other programming languages too.

Syntax

The syntax of the for loop is like below.

  • VAL is used in each iteration to set current element value.
  • SEQUENCE is the list, an array of the values those will be iterated.
  • STATEMENT will be executed in each iteration. We can also call is the body of the for loop.

For Loop

We will start with a simple for loop example. We will iterate over the given list which will start from 1 and count to the 10 .We will print each element in each iteration.

For Loop

For Loop

We can see that each element is printed to the standard output.

Vector For Loop

Vector is a very popular and useful data structure in R programming language. We will create a Vector which holds years from 2015 to 2019. Then we will iterate over this vector and print each element to the standard output.

Vector For Loop

Vector For Loop

Matrix For Loop

Matrix is another useful data type used in the R programming language. We can also call matrix as multi-level array or vector. We can iterate over given matrix by using multiple and nested for loops. We will create a matrix which is 4×4 and then print to the screen accordingly.

LEARN MORE  Javascript For and While Loop Iteration

 

 

Nested For Loop

We have all ready used some nested for loop in previous example. We can use nested or multi level loops with for like below. We will use 3 level and start from 1 to 3 and multiple them.

Nested For Loop

Nested For Loop

Using Next Statement To Skip Iteration

During the iteration of the for loop we may need to skip for specific iterations. We can use next  statement to skip specified iterations or cases. In this example, we will skip odd numbers.

Using Next Statement

Using Next Statement

Leave a Reply

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

Enjoy this blog? Please spread the word :)