You are currently viewing R Using For in Range with Example

The for in range in R is a syntax to iterate for loop with a range of values from starting and ending position. Someone asked me how to use for i in range in R programming in comments, I would like to take some time to cover this with a few examples.

Advertisements

If you are not familiar with for loop in R, the for loop is used to repeatedly execute a set of statements or block of code for every element in a sequence or range. The for loop is always used with sequence objects like a list, vector, or array. Loop continues until we reach the last item in the sequence or until the break statement encounter. 

1. Syntax of for in Range

Below is the syntax of for in a range of values. Here, the range is the range of values that contains start:stop.


# for in range syntax
for (var in range) {
    # statement(s)    
}

2. for in Range of Numeric Values in R

By using for we can execute the block of code repeatedly for all elements in a range in R. The below example uses 5:10 range which ideally creates a vector with numeric values between 5 and 10 (including start and end values).


# for i in range example
numeric_range <- 5:10
for(i in numeric_range) { 
  print(paste("i value : ", i))
}

Yields below output. This example prints values from starting and ending to the console.

for i in range

You can also write the above statement as follows (using the range within for loop).


# for i in letters range example
for(i in 5:10) { 
  print(paste("i value : ", i))
}

Yields the same output as above.

3. for in Range of Letters

Similarly, you can also use for with a range of letters. To get the range of letters you should use LETTERS[start:stop]. Here, the start and stop would be numeric values and it returns the alphabet of the number position.


# for i in letters range example
for(i in LETTERS[2:5]) { 
  print(paste("i value : ", i))
}

Yields below output.

for i in range r

Conclusion

In this article, you have learned how to use for i in range by R example. Also, learned for with a range of letters. To get the range of letters you should use LETTERS[start:stop]. The for in range in R is a syntax to iterate for loop with a range of values from starting to ending position.

Related Articles

References

Naveen Nelamali

Naveen Nelamali (NNK) is a Data Engineer with 20+ years of experience in transforming data into actionable insights. Over the years, He has honed his expertise in designing, implementing, and maintaining data pipelines with frameworks like Apache Spark, PySpark, Pandas, R, Hive and Machine Learning. Naveen journey in the field of data engineering has been a continuous learning, innovation, and a strong commitment to data integrity. In this blog, he shares his experiences with the data as he come across. Follow Naveen @ LinkedIn and Medium