VOOZH about

URL: https://www.geeksforgeeks.org/r-language/how-to-create-a-for-loop-with-range-in-r/

⇱ How to Create a For Loop with Range in R? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Create a For Loop with Range in R?

Last Updated : 11 Apr, 2022

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

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

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:

Output:

[1] 2 3 1 2 3 4 5
Comment
Article Tags:
Article Tags:

Explore