R If...Else Conditions

"If-else" statements in R are control structures that allow you to make decisions in your code based on specified conditions. They provide a way to execute different blocks of code depending on whether a given condition is true or false. Here's a detailed explanation with examples:

if (condition) { # Code to execute if the condition is true } else { # Code to execute if the condition is false }

The condition is a logical expression that evaluates to either TRUE or FALSE. If the condition is TRUE, the first block of code is executed. Otherwise, the second block of code is executed.

Simple If-Else

age <- 18 if (age >= 18) { print("You are an adult.") } else { print("You are a minor.") } #Output:"You are an adult."

In the above example, the program checks whether the age variable is greater than or equal to 18. If it is, the message "You are an adult." is printed; otherwise, "You are a minor." is printed.

Nested If-Else

temperature <- 25 if (temperature > 30) { print("It's hot outside.") } else if (temperature > 20) { print("It's a pleasant day.") } else { print("It's a bit cool.") } #Output:"It's a pleasant day."

The above example demonstrates a nested "if-else" statement, where the program assesses the temperature variable and provides different messages based on the temperature range.

Using If-Else for Data Processing

scores <- c(85, 92, 78, 65, 98) passing_threshold <- 70 num_passing <- 0 for (score in scores) { if (score >= passing_threshold) { num_passing <- num_passing + 1 } } print(paste("Number of passing scores:", num_passing)) #Output: "Number of passing scores: 4"

The above example uses an "if-else" statement within a loop to count the number of passing scores in a list of scores based on the passing_threshold.


"If-else" statements are invaluable for implementing decision-making logic in your code, enabling it to adapt and respond to different scenarios. They are essential for branching the execution path and tailoring the behavior of your program according to specific conditions.