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
R
for (i in 1: 5) {
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
for (i in 1: 5) {
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
vector1 = c (2, 3)
for (i in 1: 5) {
vector1 = c (vector1, i)
}
vector1
|
Output:
[1] 2 3 1 2 3 4 5
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...