0
0
R Programmingprogramming~5 mins

If-else statements in R Programming

Choose your learning style9 modes available
Introduction

If-else statements help your program make choices. They let your code do different things based on conditions.

Deciding if a number is positive or negative.
Checking if a user is old enough to access a website.
Choosing what message to show based on the time of day.
Running different code when a button is clicked or not.
Syntax
R Programming
if (condition) {
  # code to run if condition is TRUE
} else {
  # code to run if condition is FALSE
}
The condition is a test that is either TRUE or FALSE.
Use curly braces { } to group the code that runs for each case.
Examples
This checks if x is greater than zero. If yes, it prints "Positive number"; otherwise, it prints "Not positive".
R Programming
x <- 5
if (x > 0) {
  print("Positive number")
} else {
  print("Not positive")
}
This checks if age is 18 or more. It prints "Adult" if true, else "Minor".
R Programming
age <- 17
if (age >= 18) {
  print("Adult")
} else {
  print("Minor")
}
Sample Program

This program checks the temperature. If it is above 25, it says it's hot; otherwise, it says it's not hot.

R Programming
temperature <- 30
if (temperature > 25) {
  print("It's hot outside")
} else {
  print("It's not hot outside")
}
OutputSuccess
Important Notes

You can add more conditions using else if for multiple choices.

Make sure your conditions are clear and use logical operators like && (and), || (or) if needed.

Summary

If-else lets your program choose between two paths.

Use conditions that are TRUE or FALSE to decide what runs.

Curly braces group the code for each choice.