R Programming While and For Loops

R Programming while loops take on the same syntax as seen in JavaScript, C, C#, and many other languages. However, with for loops the iterator style reflects something like a combination of Python iterator syntax mixed with aforementioned languages’ parenthesis and curly braces. This post will cover R Programming while and for loops and also details some other observations about R Studio and the console I picked up along the way.

The official documentation for “repetitive execution” is here – https://cran.r-project.org/doc/manuals/r-release/R-intro.html#Repetitive-execution

The general structure of for and while loops is:

for(<condition>) {<logic>} and while(<condition>) {<logic>}

So, unlike Python, we see the condition and business logic separated as with JavaScript,C, and C# using parenthesis and curly braces. Below are examples which further illustrate the syntax.

While Loop

a <- 0

while (a < 10) {
a <- a + 1
print(a) # required to print in loops (instead of just specifying variable)
}
a # now 10

Nothing too interesting there. One note is that, thus far in R Studio, I’ve observed variables can/will be printed to the console without requiring a print() function call. Within loops, print() is required. I will start using print() for all console output moving forward simply per my preference.

Also, I found this StackOverflow post when checking to see if there is do...while syntax supported:

https://stackoverflow.com/questions/4357827/do-while-loop-in-r

So, no, there isn’t do...while, but there is a good substitute with repeat and an if condition.

For Loop

floop <- 0

for(floop in 1:5) { # “vector <1,2,3,4,5>”
print(paste(“floop is now”,floop))
}

The “1:5” syntax to step/iterate reflects the strong reliance on vectors in R Programming. I’m yet to get deep into vectors so won’t comment further until more dedicated notes about vectors and use cases are published. Also, that syntax recalls what one encounters Python array iterators (e.g. [1:5]) minus the step parameter.

R Studio and the GUI Console

I picked up another nugget while practicing with for and while loops. The Console window is fully interactive.

In my first post about R Programming, I covered the R Studio installation process. That post contains a screen shot showing the interactive R GUI console. Though the console in R Studio isn’t full-fidelity to the complete RGUI console, it does support a complete interactive “REPL” type functionality . Nothing Earth-shattering, but it was a nice find as I explore the GUI further.

R GUI console embedded in R Studio.

A final note about this console: the Esc key can be used to halt execution if accidentally invoking an infinite loop.

That concludes these notes on R Programming while and for loops.



Categories: R Programming

Tags: ,

1 reply

Trackbacks

  1. Vectors in R Programming - Westmorr Consulting

Leave a Reply

%d