Basic R Programming | Control Flow Statements in R

Control flow is where the rubber really meets the road in programming. Without it, a program is simply a list of statements that are sequentially executed. With control flow, you can execute certain code blocks conditionally and/or repeatedly, these basic building blocks can be combined to create surprisingly sophisticated programs!


Conditional Statements: 
R supports two types of conditional statements

  • If…else : In if...else statements, when the test expression is True, the code in the “if” block executes; otherwise, the code in the “else” block executes.
  • Nested if…else : In nested if...else statements, only one statement executes, depending on the test expressions in the “if” blocks.
  • Ifelse() : This is a vector equivalent form of if…else.
  • Switch Function : This is similar to a controlled branch of if…else statements

For Loops
Loops in Rare a way to repeatedly execute some code statement. So, for example, if we'd like to print each of the items in a list, we can use a for loop:
While loops
The argument of the while loop is evaluated as a boolean statement, and the loop is executed until the statement evaluates to False.
Repeat loops
A repeat loop iterates a code multiple times. Since there is no conditional check to exit the loop, you must specify it inside the body of the loop.
next and break: Fine-Tuning Your Loops
There are two useful statements that can be used within loops to fine-tune how they are executed:
  • The next statement skips the remainder of the current loop, and goes to the next iteration
  • The break statement breaks-out of the loop entirely
These can be used in both for and while loops.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.