Conditional Constructs in R
Conditional constructs in R allow you to control the flow of your program based on conditions. They enable you to execute certain blocks of code depending on whether a condition is true or false. R provides several constructs for conditionally executing code:
if statement
if...else statement
if...else if...else statement
switch statement
Let’s go through each of these constructs in detail.
The if statement is the most basic conditional statement in R. It allows you to execute a block of code only if a condition is TRUE. If the condition is FALSE, the block of code is skipped.
Syntax:
R
if (condition) {
# Code to execute if condition is TRUE
}
condition: A logical expression that is evaluated.
If the condition evaluates to TRUE, the code inside the curly braces is executed.
Example 1: Simple if Statement
R
x <- 5
if (x > 0) {
print("x is positive")
}
Output:
csharp
[1] "x is positive"
In this example, since x > 0 is TRUE, the message "x is positive" is printed.
The if...else statement allows you to specify an alternative block of code to execute if the condition is FALSE. If the condition is TRUE, the first block of code runs; otherwise, the else block is executed.
Syntax:
R
if (condition) {
# Code to execute if condition is TRUE
} else {
# Code to execute if condition is FALSE
}
Example 2: if...else Statement
R
x <- -3
if (x > 0) {
print("x is positive")
} else {
print("x is non-positive")
}
Output:
csharp
[1] "x is non-positive"
In this case, since x is not greater than 0, the else block is executed, printing "x is non-positive".
The if...else if...else statement allows you to test multiple conditions sequentially. If the first condition is FALSE, the next condition in the else if part is tested, and so on. If none of the conditions are TRUE, the else block is executed.
Syntax:
R
if (condition1) {
# Code to execute if condition1 is TRUE
} else if (condition2) {
# Code to execute if condition2 is TRUE
} else {
# Code to execute if all conditions are FALSE
}
Example 3: if...else if...else Statement
R
x <- 0
if (x > 0) {
print("x is positive")
} else if (x < 0) {
print("x is negative")
} else {
print("x is zero")
}
Output:
csharp
[1] "x is zero"
In this example, since x is neither greater than nor less than 0, the else block is executed, and "x is zero" is printed.
The switch statement is used when you need to choose from multiple possible options, usually based on a variable's value. It evaluates an expression and matches it against a list of possible values.
Syntax:
R
switch(expression,
case1 = { # Code to execute if expression matches case1 },
case2 = { # Code to execute if expression matches case2 },
case3 = { # Code to execute if expression matches case3 },
...
)
The expression is evaluated, and the corresponding case is executed.
If no match is found, the switch function returns NULL.
Example 4: switch Statement
R
day <- 3
result <- switch(day,
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
)
print(result) # Output: "Tuesday"
In this example, the variable day is assigned the value 3. The switch statement matches 3 to the third option in the list, which is "Tuesday", and prints it.
You can combine multiple conditions using logical operators like & (AND), | (OR), ! (NOT). These allow for more complex conditional checks.
&: Logical AND (both conditions must be true)
|: Logical OR (at least one condition must be true)
!: Logical NOT (reverses the condition)
Example 5: Using & (AND) and | (OR)
R
x <- 5
y <- 10
if (x > 0 & y > 5) {
print("Both conditions are true")
}
if (x < 0 | y > 5) {
print("At least one condition is true")
}
Output:
csharp
[1] "Both conditions are true"
[1] "At least one condition is true"
In this example:
The first condition (x > 0 & y > 5) checks if both x is greater than 0 and y is greater than 5.
The second condition (x < 0 | y > 5) checks if either x is less than 0 or y is greater than 5.
In R, missing values are represented by NA. To check whether a variable contains a missing value, you can use the is.na() function.
Example 6: Using is.na()
R
x <- NA
if (is.na(x)) {
print("x is missing")
} else {
print("x has a value")
}
Output:
csharp
[1] "x is missing"
In this case, the is.na(x) condition checks if x is NA, and since it is, the message "x is missing" is printed.
R also provides functions like stop() and warning() for error handling and generating warnings. These functions can be used in conditional statements to halt execution or provide warnings.
stop(): Stops execution and throws an error.
warning(): Issues a warning but continues execution.
Example 7: Using stop() and warning()
R
x <- -5
if (x < 0) {
stop("x cannot be negative") # This will stop execution
}
y <- 50
if (y > 10) {
warning("y is greater than 10, but execution continues")
}
Output:
javascript
Error: x cannot be negative
In this case, the stop() function is triggered because x is negative, stopping the execution of the code. If the warning condition is met, warning() will display a message but will allow the program to continue.
if statement: Executes code if a condition is TRUE.
if...else statement: Executes one block of code if the condition is TRUE, and another if it is FALSE.
if...else if...else statement: Tests multiple conditions and executes corresponding blocks of code.
switch statement: Used to select from multiple options based on a value.
Logical operators: Combine multiple conditions in a more complex conditional statement using &, |, and !.
is.na(): Checks if a value is missing (NA).
stop() and warning(): Used for error handling and issuing warnings.
These conditional constructs allow you to write flexible and efficient code that can respond to different inputs and conditions dynamically.