How to create a column based on conditions in R

· 1 min read · Updated March 14, 2026 · beginner
r ifelse case_when dplyr conditional transformation

Creating conditional columns lets you derive new values based on logic.

With dplyr and ifelse()

The ifelse() function works like a ternary operator:

library(dplyr)

df <- df %>%
  mutate(category = ifelse(sales > 1000, "High", "Low"))

With dplyr and case_when()

For multiple conditions, case_when() is cleaner:

library(dplyr)

df <- df %>%
  mutate(
    tier = case_when(
      sales > 1000 ~ "Premium",
      sales > 500 ~ "Standard",
      TRUE ~ "Basic"
    )
  )

The TRUE ~ "Basic" acts as an else catch-all.

With base R

Base R has a few options:

# Using ifelse()
df$category <- ifelse(df$sales > 1000, "High", "Low")

# Using if() for single conditions
if (df$sales[1] > 1000) {
  df$category[1] <- "High"
}

With data.table

data.table uses a similar syntax:

library(data.table)

dt[, category := ifelse(sales > 1000, "High", "Low")]

# Or with fifelse (faster)
dt[, category := fifelse(sales > 1000, "High", "Low")]

Common Patterns

Numeric thresholds

df <- df %>%
  mutate(
    performance = case_when(
      score >= 90 ~ "Excellent",
      score >= 70 ~ "Good",
      score >= 50 ~ "Fair",
      TRUE ~ "Needs Improvement"
    )
  )

Multiple conditions

df <- df %>%
  mutate(
    segment = case_when(
      age > 65 & income > 50000 ~ "Senior Affluent",
      age > 65 ~ "Senior",
      income > 50000 ~ "Affluent",
      TRUE ~ "Standard"
    )
  )

See Also