for-Loop with Range in R (Example)
This article explains how to write a for-loop with range in the R programming language.
The tutorial looks as follows:
Here’s the step-by-step process.
Example: Looping Over Range of Numeric Values
This Example explains how to write and run a for-loop through a range of numeric values in R. First, we have to create an example range:
my_range <- 5:10 # Create numeric range my_range # Print range # 5 6 7 8 9 10
Have a look at the previous output of the RStudio console. We have created a vector object containing numeric elements ranging from 5 to 10.
Let’s for-loop over this range!
for(i in my_range) { # Head of for-loop print(paste("This iteration represents range value", i)) # Code block } # [1] "This iteration represents range value 5" # [1] "This iteration represents range value 6" # [1] "This iteration represents range value 7" # [1] "This iteration represents range value 8" # [1] "This iteration represents range value 9" # [1] "This iteration represents range value 10"
To loop through our numeric range, we simply had to specify this range in the head of our for-loop. The RStudio output shows the result of our for-loop: Some sentences representing the current value of our range in each iteration of the for-loop.
Video, Further Resources & Summary
Would you like to learn more about loops in the R programming language? Then you could watch the following video of my YouTube channel. In the video, I explain the R programming syntax of this tutorial:
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
Furthermore, you could read the related tutorials which I have published on my homepage. I have published several tutorials already.
Summary: You learned in this article how to use for-loops with range in R programming. If you have additional questions, don’t hesitate to let me know in the comments section.