Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

If-Else Statements in R

Introduction

If-else statements are fundamental control structures in programming that allow you to execute different blocks of code based on certain conditions. In R, the if-else structure is crucial for making decisions and controlling the flow of your program.

Basic Syntax

The basic syntax of an if-else statement in R is as follows:

if (condition) {

# code to execute if condition is true

} else {

# code to execute if condition is false

}

Here, condition is a logical expression that evaluates to either TRUE or FALSE. Depending on the result, the corresponding block of code will be executed.

Example of If-Else Statement

Let's take a look at a simple example where we check if a number is positive or negative:

number <- -5

if (number > 0) {

print("The number is positive.")

} else {

print("The number is negative or zero.")

}

In this example, since the variable number is -5, the output will be:

The number is negative or zero.

Using Else If

Sometimes you may want to check multiple conditions. In such cases, you can use else if to handle multiple cases:

score <- 85

if (score >= 90) {

grade <- "A"

} else if (score >= 80) {

grade <- "B"

} else {

grade <- "C"

}

print(grade)

For the score of 85, the output will be:

B

Conclusion

If-else statements are a powerful way to control the flow of your R programs. By allowing you to execute different blocks of code based on conditions, they enable you to create dynamic and responsive applications. Practice using if-else statements to become more proficient in R programming!