How to Create a For Loop with Range in R?
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
Example 1: Print values in a range
R
# create a range with 1 to 5 numbers for (i in 1: 5) { # display the values print (i) } |
Output:
[1] 1 [1] 2 [1] 3 [1] 4 [1] 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) { //operations }
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 numbers for (i in 1: 5) { # display the values by performing # square of numbers print (i*i) } |
Output:
[1] 1 [1] 4 [1] 9 [1] 16 [1] 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 vector vector1 = c (2, 3) # create a range with 1 to 5 numbers for (i in 1: 5) { # append values to a vector vector1 = c (vector1, i) } # display vector1 |
Output:
[1] 2 3 1 2 3 4 5
Please Login to comment...