Conditional Statements in R (if, else, switch)
Join our community on Telegram!
Join the biggest community of Pharma students and professionals.
Conditional statements in R are used to make decisions in a program. They allow the code to perform different actions based on whether a condition is true or false. This is very useful when you want your program to react differently depending on the data or user input.
The most basic conditional statement is the if statement. It checks whether a condition is true. If the condition is true, the code inside the if block is executed. If the condition is false, the code is skipped. For example, if you have a variable marks <- 75, you can write an if statement to check whether the marks are greater than 50. If the condition is true, the program can display a message such as “You passed the exam.”
When you want the program to perform one action if the condition is true and another action if the condition is false, you use the if…else statement. In this case, if the condition is true, the code inside the if block runs. If the condition is false, the code inside the else block runs. For example, if marks <- 40, the condition marks > 50 becomes false, so the else part can display a message like “You did not pass the exam.” This helps the program choose between two possible outcomes.
Sometimes you may have multiple conditions to check. In such cases, you can use else if along with if and else. For example, you might want to assign grades based on marks. If the marks are above 90, the grade is A. If the marks are between 75 and 90, the grade is B. If the marks are between 50 and 75, the grade is C. Otherwise, the grade is D. The program checks each condition one by one and executes the first one that is true.
R also provides a switch statement, which is useful when you have multiple possible values for a variable and want to select one specific action based on that value. Instead of writing many if…else conditions, switch allows you to choose a result directly. For example, if a variable day <- "Monday", the switch statement can return “Start of the work week.” If the value is “Sunday,” it can return “Holiday.” This makes the code shorter and easier to read when dealing with many options.
Conditional statements are important because they allow programs to make decisions, control the flow of execution, and respond to different situations. They are commonly used in data analysis, user input handling, and automation tasks in R.
