R Control Statements
R Control Statements
Tutorial Name: Codes With Pankaj Website: www.codeswithpankaj.com
Table of Contents
Introduction to Control Statements
Conditional Statements
if Statement
if...else Statement
ifelse() Function
Nested if...else
Switch Statement
Looping Statements
for Loop
while Loop
repeat Loop
Break and Next Statements
1. Introduction to Control Statements
Control statements in R allow you to control the flow of your program by executing specific code blocks based on conditions or by iterating over data structures. These statements are essential for decision-making, looping, and managing code execution.
2. Conditional Statements
Conditional statements are used to perform different actions based on different conditions.
2.1 if Statement
The if
statement executes a block of code if the specified condition is TRUE
.
Syntax:
Example:
2.2 if...else Statement
The if...else
statement allows you to execute one block of code if the condition is TRUE
and another block if the condition is FALSE
.
Syntax:
Example:
2.3 ifelse() Function
The ifelse()
function is a vectorized version of the if...else
statement. It checks a condition and returns one value if TRUE
and another if FALSE
.
Syntax:
Example:
2.4 Nested if...else
You can nest multiple if...else
statements to check multiple conditions.
Example:
3. Switch Statement
The switch
statement evaluates an expression and executes a block of code based on the value of that expression.
Syntax:
Example:
4. Looping Statements
Looping statements allow you to repeat a block of code multiple times.
4.1 for Loop
The for
loop is used to iterate over a sequence (e.g., a vector or list).
Syntax:
Example:
4.2 while Loop
The while
loop repeats a block of code as long as the specified condition is TRUE
.
Syntax:
Example:
4.3 repeat Loop
The repeat
loop executes a block of code repeatedly until a break
statement is encountered.
Syntax:
Example:
5. Break and Next Statements
5.1 Break Statement
The break
statement is used to exit a loop prematurely when a certain condition is met.
Example:
5.2 Next Statement
The next
statement is used to skip the current iteration of a loop and move to the next iteration.
Example:
Conclusion
Control statements are fundamental in R programming as they allow you to control the flow of execution and make decisions in your code. By mastering these statements, you can create more complex and dynamic R programs.
For more tutorials and resources, visit Codes With Pankaj at www.codeswithpankaj.com.
Last updated