</>
Skip to content
R lessons (17/41)

R — Conditions

The if statement

age <- 25

if (age >= 18) {
  print("You are an adult.")
}

The condition must be a logical value. Parentheses around the condition are required. Curly braces define the code block.

The if-else statement

temperature <- 5

if (temperature > 30) {
  print("It's hot outside.")
} else {
  print("It's not that hot.")
}

One of the two blocks always executes. The else must be on the same line as the closing }.

if-else-if chains

score <- 78

if (score >= 90) {
  grade <- "A"
} else if (score >= 80) {
  grade <- "B"
} else if (score >= 70) {
  grade <- "C"
} else if (score >= 60) {
  grade <- "D"
} else {
  grade <- "F"
}

print(paste("Grade:", grade))

R evaluates conditions top to bottom and runs the first matching block.

The ifelse() function

Vectorized version of if-else — works on entire vectors:

x <- c(1, -2, 3, -4, 5)

# ifelse(condition, yes, no)
result <- ifelse(x > 0, "positive", "negative")
print(result)  # "positive" "negative" "positive" "negative" "positive"

# Useful for transformations
grades <- ifelse(score >= 90, "A",
          ifelse(score >= 80, "B",
          ifelse(score >= 70, "C",
          ifelse(score >= 60, "D", "F"))))

ifelse() returns a vector the same length as the condition. It's efficient for element-wise operations.

if() vs ifelse()

# if() — for scalar conditions
x <- 5
if (x > 0) print("positive")

# ifelse() — for vector conditions
x <- c(1, -2, 3)
ifelse(x > 0, "pos", "neg")  # "pos" "neg" "pos"

Don't use if() on vectors — it only checks the first element and gives a warning.

The switch() function

Compare a value against multiple options:

day <- "Monday"

result <- switch(day,
  "Monday" = "Start of the week",
  "Friday" = "TGIF!",
  "Saturday" = "Weekend",
  "Sunday" = "Weekend",
  "Invalid day"
)

print(result)  # "Start of the week"

switch() is cleaner than long if-else chains for matching against known values.

switch with numeric index

x <- 2
result <- switch(x,
  "first",
  "second",
  "third",
  "fourth"
)

print(result)  # "second"

When the first argument is numeric, switch() uses it as an index.

Nested conditions

has_ticket <- TRUE
age <- 16

if (has_ticket) {
  if (age >= 18) {
    print("Welcome to the show.")
  } else {
    print("You need a guardian.")
  }
} else {
  print("Please buy a ticket.")
}

Nesting works but becomes hard to read. Combine conditions with && and ||:

if (has_ticket && age >= 18) {
  print("Welcome!")
} else if (has_ticket) {
  print("Need a guardian.")
} else {
  print("Buy a ticket.")
}

Logical operators in conditions

x <- 5

# AND — both must be true
if (x > 0 && x < 10) {
  print("Between 0 and 10")
}

# OR — at least one must be true
if (x < 0 || x > 100) {
  print("Out of range")
}

# NOT — flips the value
if (!is.na(x)) {
  print("Not missing")
}

Use && and || in if() conditions. Use & and | for vectorized operations.

Missing values in conditions

x <- NA

# NA propagates through conditions
if (x > 0) print("positive")  # condition evaluates to NA — error!

# Handle NAs explicitly
if (!is.na(x) && x > 0) {
  print("positive")
}

# Using ifelse — handles NAs automatically
ifelse(c(1, NA, 3) > 2, "big", "small")
# "small" NA "big"

Combining conditions with complex logic

age <- 25
has_id <- TRUE
is_vip <- FALSE

# Complex condition
if (age >= 18 && has_id && !is_vip) {
  print("Standard entry")
} else if (is_vip) {
  print("VIP lane")
} else {
  print("Entry denied")
}

Vectorized if-else with dplyr

library(dplyr)

mtcars <- mtcars %>%
  mutate(
    efficiency = case_when(
      mpg > 30 ~ "Excellent",
      mpg > 20 ~ "Good",
      mpg > 15 ~ "Average",
      TRUE ~ "Poor"
    )
  )

case_when() is dplyr's version of multiple if-else — clean and vectorized.

Common mistakes

Forgetting parentheses

# if x > 0    # Syntax error
if (x > 0) { }  # correct

Using = instead of ==

# if (x = 5) { }  # Error: argument is not interpretable as logical
if (x == 5) { }   # correct

Missing the curly brace alignment

# Ambiguous — only the next line is conditional
if (x > 0)
  print("positive")
  print("always runs")  # this is NOT inside the if!

# Always use braces
if (x > 0) {
  print("positive")
  print("also conditional")
}

If with functions

divide <- function(a, b) {
  if (b == 0) {
    return(NA)
  }
  a / b
}

divide(10, 3)   # 3.333...
divide(10, 0)   # NA

Mini Practice

  1. Write a program that classifies a number as positive, negative, or zero
  2. Use ifelse() to double all positive numbers in a vector and set negatives to 0
  3. Create a grade calculator using switch() with letter grades
  4. Use case_when() from dplyr to categorize mtcars$mpg into efficiency levels
  5. Write a function that returns "even" or "odd" for a given number using if-else

Next: loops — repeating actions →

Related Topics

Frequently Asked Questions about Conditions

What is Conditions in R?

Conditions is a fundamental concept in R. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Conditions?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Conditions.

Why is Conditions important in R?

Conditions is essential for R development. Understanding this concept will help you write better code and solve real-world problems more effectively.