Monday, September 24, 2018

Introduction to R: Control Structure in R Part 2

"While" Loop Function
A while loop begins by testing a logical expression then executes a loop body based on the value of the logical expression. Once the loop is executed, the condition is tested again until the loop is terminated when a limit is reached.

Example: Create a while loop that will print out a value from 1 to 20 and will terminate at the value of 20.



In the example the while loop takes a logical expression that counts from 1 to 20, and prints the value. If the count reaches 20, the loop stops or terminated.

Although the while loop make things easier to read, this type of loop can potentially result in infinite loops when the command is not written properly SO USE WITH CARE. It is safer to use a for {} loop when you have a complex command.


No comments:

Post a Comment