How to Create a For Loop with Range in R?

• Last Updated : 28 Nov, 2021

In this article, we will discuss how to create a for loop with range in R Programming Language.

For loop is used to iterate the elements over the given range. We can use for loop to append, print, or perform some operation on the given range of integers. Consider the below syntax of the for loop that also contains some range in it.

Syntax:

for(iterator in range) {
# statements
}

where,

• range is the range of values that contains start:stop
• iterator is  available used to iterate the elements over the given range

R

 # create a range with 1 to 5 numbersfor(i in 1: 5) {        # display the values    print(i)}

Output:

 1
 2
 3
 4
 5

Example 2: Perform Operation on Values in Range

We can also perform some mathematical operations over the range of values inside for loop.

Syntax:

for(iterator in range) {
//oerations
}

where,

• range is the range of values that contains start:stop
• iterator is  available used to iterate the elements over the given range
• operations is used to perform some mathematical operations

R

 # create a range with 1 to 5 numbersfor(i in 1: 5) {          # display the values by performing     # square of numbers    print(i*i)}

Output:

 1
 4
 9
 16
 25

Example 3: Performing operations on values in a vector

Here we are going to append the values to the vector by using for loop.

Syntax:

for(iterator in range) {
vector=c(vector,iterator )
}

Example:

R

 # create a vectorvector1 = c(2, 3)  # create a range with 1 to 5 numbersfor(i in 1: 5) {          # append values to a vector    vector1 = c(vector1, i)}  # displayvector1

Output:

 2 3 1 2 3 4 5

My Personal Notes arrow_drop_up