dplyr case_when() in R: A Practical Guide with Examples
Use dplyr case_when() to create new columns and classify data using multiple conditions. Start with simple rules, then learn ordered conditions, missing values, recoding, grouped summaries, and advanced data-cleaning examples.
What does case_when() do in R?
case_when() is a dplyr function in R for applying multiple conditions and returning a value for each row. It is especially useful when you want to create categories such as pass/fail, low/medium/high, customer segments, risk bands, or sales performance labels.
Think of case_when() as a set of ordered rules: if a condition is true, return its corresponding result. R checks the rules from top to bottom and uses the first matching rule for each row.
case_when(
condition_1 ~ result_1,
condition_2 ~ result_2,
condition_3 ~ result_3
)
Most often, you use case_when() inside mutate() to create a new variable or update an existing one. If you are new to dplyr, start with the dplyr tutorial overview, then learn mutate() to create columns.
Remember: each rule follows the pattern condition ~ value. The tilde separates the condition on the left from the value to return on the right.
Create example data for case_when()
We will use a small student dataset with exam scores, attendance, and department. These examples start with simple classifications and gradually introduce more realistic data-analysis tasks. The missing score for Maya will also help demonstrate how to handle missing values safely.
library(dplyr)
students <- tibble(
student = c("Amina", "Bilal", "Sara", "Omar", "Noor", "Hassan", "Maya", "Zain"),
score = c(92, 76, 58, 43, 81, 67, NA, 35),
attendance = c(96, 82, 74, 68, 91, 88, 79, 52),
department = c("Business", "Computing", "Business", "Computing",
"Statistics", "Business", "Statistics", "Computing")
)
students
| student | score | attendance | department |
|---|---|---|---|
| Amina | 92 | 96 | Business |
| Bilal | 76 | 82 | Computing |
| Sara | 58 | 74 | Business |
| Omar | 43 | 68 | Computing |
| Noor | 81 | 91 | Statistics |
| Hassan | 67 | 88 | Business |
| Maya | 79 | Statistics | |
| Zain | 35 | 52 | Computing |
The aim is not just to label scores. The same technique can classify sales, customer activity, survey responses, product performance, waiting times, and many other variables.
Your first case_when() example
Start with a single condition. Suppose you want to label scores of 50 or above as "Pass" and all other scores as "Review". Use a final TRUE condition as the fallback:
students |>
mutate(result = case_when(
score >= 50 ~ "Pass",
TRUE ~ "Review"
))
The first rule labels scores of 50 or higher. The final rule catches every remaining row, including scores below 50. In this first version, a missing score also falls through to the default label, so use an explicit missing-value rule when you need to distinguish unknown scores from low scores.
Understand each part
mutate(result = ...)creates a column namedresult.score >= 50is the condition being tested for each row.~ "Pass"is the value returned when the condition is true.TRUE ~ "Review"provides a default for rows that did not match earlier rules.
To keep the new column for later analysis, assign the result to an object:
students_result <- students |>
mutate(result = case_when(
score >= 50 ~ "Pass",
TRUE ~ "Review"
))
Create pass and fail categories
A common beginner use of case_when() is to classify students as passing or failing. The following example adds a separate label for a missing score, which is usually more informative than treating missing data as a failure.
students |>
mutate(result = case_when(
is.na(score) ~ "No score recorded",
score >= 50 ~ "Pass",
score < 50 ~ "Fail"
))
Because missingness is checked first, Maya is labelled "No score recorded". Students with a recorded score of 50 or more pass, and recorded scores below 50 fail. This example assumes 50 is the relevant pass threshold; always use the grading rules appropriate to your institution.
Return a logical result instead of a label
If you only need a TRUE/FALSE indicator, a direct comparison may be simpler than case_when():
students |>
mutate(passed = score >= 50)
This returns TRUE for scores at least 50, FALSE for scores below 50, and NA when the score is missing. Use case_when() when you need several labels or more complicated rules.
Classify values into multiple ranges
Often you need more than two categories. For example, an analyst might classify scores as Excellent, Good, Pass, or Needs Improvement. Write one condition for each band:
students |>
mutate(grade = case_when(
is.na(score) ~ "Not assessed",
score >= 80 ~ "Excellent",
score >= 70 ~ "Good",
score >= 50 ~ "Pass",
score < 50 ~ "Needs improvement"
))
The result is a categorical description based on the numeric score. Because the missing-value rule is first, missing scores are not accidentally labelled as a low grade.
Why can later conditions use shorter ranges?
After the rule score >= 80 has matched all scores of 80 or higher, the next rule score >= 70 only needs to catch the remaining scores of 70–79. This works because the first matching condition wins. You could write score >= 70 & score < 80 explicitly, which may be easier to understand in some cases.
students |>
mutate(grade = case_when(
is.na(score) ~ "Not assessed",
score >= 80 & score <= 100 ~ "Excellent",
score >= 70 & score < 80 ~ "Good",
score >= 50 & score < 70 ~ "Pass",
score < 50 ~ "Needs improvement",
TRUE ~ "Check score"
))
The explicit bounds also make it easier to catch unexpected values such as scores above 100. The final fallback is useful for quality control, but it should not replace checking whether the data are valid.
Why condition order matters in case_when()
Condition order is one of the most important parts of using dplyr case_when(). The function returns the value associated with the first matching condition. Put the most specific rules before broad rules.
Consider this incorrect example:
students |>
mutate(grade = case_when(
score >= 50 ~ "Pass",
score >= 80 ~ "Excellent",
TRUE ~ "Fail"
))
A score of 92 matches score >= 50 first, so it is labelled Pass. The Excellent rule never gets a chance to classify that row. Put the higher threshold first:
students |>
mutate(grade = case_when(
is.na(score) ~ "Not assessed",
score >= 80 ~ "Excellent",
score >= 50 ~ "Pass",
TRUE ~ "Fail"
))
Rule of thumb: when rules overlap, put the narrowest or most specific condition first, followed by broader conditions and then a fallback.
Use a default or fallback category
A final TRUE ~ ... rule is a convenient way to handle values not matched by previous conditions. It can prevent unwanted missing results when you want every row to receive a label.
students |>
mutate(attendance_band = case_when(
attendance >= 90 ~ "High attendance",
attendance >= 75 ~ "Moderate attendance",
TRUE ~ "Low attendance"
))
In this example, attendance below 75 is labelled Low attendance. If the attendance column itself contained missing values, the fallback would also label those rows Low attendance. If missing attendance should mean unknown, test is.na(attendance) first.
students |>
mutate(attendance_band = case_when(
is.na(attendance) ~ "Unknown",
attendance >= 90 ~ "High attendance",
attendance >= 75 ~ "Moderate attendance",
TRUE ~ "Low attendance"
))
Choose the fallback carefully. TRUE ~ "Other" is useful for classification, while a label such as "Check data" can make unexpected values easier to find.
Handle missing values with case_when()
Missing data require an explicit decision. If you want to label missing scores as "Unknown", use is.na() as one of the rules. Put it near the beginning so the missing value is clearly handled before the numeric categories.
students |>
mutate(score_band = case_when(
is.na(score) ~ "Unknown",
score >= 80 ~ "High",
score >= 50 ~ "Medium",
TRUE ~ "Low"
))
Do not use score == NA to test missing values. In R, use is.na(score). A missing value is not equal to itself in the ordinary comparison sense.
Keep missing values as NA
If you prefer to leave missing scores as missing, do not classify them as a real category. You can define rules for the known values and let missing values remain unmatched:
students |>
mutate(score_band = case_when(
score >= 80 ~ "High",
score >= 50 ~ "Medium",
score < 50 ~ "Low"
))
Because the score for Maya is missing, none of the comparisons is true for that row, so the resulting category is missing. This can be appropriate when missingness should be preserved for later analysis.
Create and recode columns with mutate()
The most common pattern is mutate(new_column = case_when(...)). You can create a new column without removing the original columns, or overwrite an existing column by assigning back to its name.
Create a new category column
students |>
mutate(performance = case_when(
is.na(score) ~ "Pending",
score >= 80 ~ "Strong",
score >= 60 ~ "Satisfactory",
TRUE ~ "Needs support"
))
Recode existing text labels
Suppose a dataset uses short department codes and you want readable names. Match the old value and return the new value:
department_data |>
mutate(department_name = case_when(
department == "BUS" ~ "Business",
department == "CMP" ~ "Computing",
department == "STA" ~ "Statistics",
TRUE ~ "Other or unknown"
))
This example assumes the source data frame is named department_data and its department column contains the codes shown. If you want to replace the original column, use mutate(department = case_when(...)) instead of creating department_name.
Use case_when() within a longer pipeline
students |>
filter(!is.na(score)) |>
mutate(grade = case_when(
score >= 80 ~ "High",
score >= 50 ~ "Pass",
TRUE ~ "Fail"
)) |>
select(student, department, score, grade)
This pipeline first removes rows with missing scores, then creates a grade, and finally keeps only the columns needed for reporting. The order of operations matters: because missing scores are filtered out, a separate missing-score label is not needed in this particular example.
Match text values and combine conditions
case_when() works with character values as well as numbers. Text comparisons should use quotation marks around the text being matched.
students |>
mutate(department_group = case_when(
department == "Business" ~ "Business studies",
department == "Computing" ~ "Technology",
department == "Statistics" ~ "Quantitative studies",
TRUE ~ "Other"
))
You can also combine a text condition with a numeric condition. For example, label a student as a priority for support when the score is below 50 or attendance is below 70. Decide how missing values should be handled for your particular task.
students |>
mutate(support_flag = case_when(
is.na(score) ~ "Check missing score",
score < 50 | attendance < 70 ~ "Priority support",
score >= 80 & attendance >= 90 ~ "Strong performance",
TRUE ~ "Routine monitoring"
))
Here, | means OR and & means AND. A row is flagged for priority support if either the score is below 50 or attendance is below 70. The missing-score rule comes first so that a missing score is not silently treated as an ordinary performance category.
Use AND, OR, and negation
More advanced classification often depends on more than one variable. In R, use & when all conditions must be true, | when at least one condition must be true, and ! to negate a logical expression.
| Operator | Meaning | Example condition |
|---|---|---|
& | AND: both conditions must be true | score >= 80 & attendance >= 90 |
| | OR: at least one condition must be true | score < 50 | attendance < 70 |
! | NOT: reverses a logical result | !is.na(score) |
Example: identify students who have a high score and strong attendance, those who need support, and everyone else.
students |>
mutate(status = case_when(
is.na(score) ~ "Score missing",
score >= 80 & attendance >= 90 ~ "High achievement",
score < 50 | attendance < 70 ~ "Needs support",
TRUE ~ "On track"
))
Use parentheses when a complicated condition could be difficult to read. Clear rules are easier to maintain and easier to explain in an analytical report.
Practical business analytics examples
Beyond student grades, case_when() can create business categories for reporting, customer segmentation, operations and finance. The thresholds below are illustrative; in a real project, choose cut-offs that fit the business context and validate them with stakeholders.
Example 1: Classify sales performance
sales_data |>
mutate(performance = case_when(
sales >= 100000 ~ "Excellent",
sales >= 50000 ~ "Good",
sales >= 20000 ~ "Average",
TRUE ~ "Below target"
))
This labels sales records by sales amount. The values are assumed to be in a numeric sales column. If sales can be missing, add is.na(sales) ~ "Unknown" before the numeric rules.
Example 2: Segment customers by spending
customers |>
mutate(segment = case_when(
is.na(total_spend) ~ "Unknown",
total_spend >= 5000 ~ "High value",
total_spend >= 1000 ~ "Regular",
total_spend > 0 ~ "Occasional",
TRUE ~ "No recorded spend"
))
This example assumes one row per customer and a numeric total_spend variable. Customer segments can support reporting and campaign planning, but spending thresholds should be adapted to the products, currency and time period being analysed.
Example 3: Categorise operational waiting times
service_calls |>
mutate(wait_category = case_when(
is.na(wait_minutes) ~ "Not recorded",
wait_minutes <= 5 ~ "Short wait",
wait_minutes <= 15 ~ "Moderate wait",
wait_minutes <= 30 ~ "Long wait",
TRUE ~ "Very long wait"
))
Because rules are evaluated in order, the second threshold catches values from above 5 through 15 after the short-wait rule has already been applied. The categories can then be counted with count() or summarised by team using group_by() and summarise().
Example 4: Create a risk band
accounts |>
mutate(risk_band = case_when(
is.na(risk_score) ~ "Unclassified",
risk_score >= 80 ~ "High risk",
risk_score >= 50 ~ "Medium risk",
risk_score >= 0 ~ "Low risk",
TRUE ~ "Check invalid score"
))
This assumes that larger numeric scores mean greater risk and valid scores range from 0 to 100. Confirm the meaning and range of a risk score before applying these labels; the direction and cut-offs vary by system.
Use case_when() with grouped data
You can create categories with case_when() before or after grouping data. For example, first classify each transaction, then count how many transactions fall into each category within each region.
sales_data |>
mutate(sales_band = case_when(
sales >= 1000 ~ "Large sale",
sales >= 500 ~ "Medium sale",
TRUE ~ "Small sale"
)) |>
count(region, sales_band)
The result contains a row for each observed region and sales-band combination. For a different question, you could group first and use summarise() to calculate the proportion of high-value transactions within each region.
sales_data |>
mutate(sales_band = case_when(
sales >= 1000 ~ "Large sale",
TRUE ~ "Other sale"
)) |>
group_by(region) |>
summarise(
transactions = n(),
large_sales = sum(sales_band == "Large sale"),
percent_large = round(100 * large_sales / transactions, 1),
.groups = "drop"
)
In this example, the percentage uses the number of rows in each region as its denominator. If the dataset contains missing sales amounts or duplicate transactions, decide how those should be handled before interpreting the percentages.
Advanced case_when() examples
Example 1: Use case_when() inside across()
For many columns with the same type, across() can apply a transformation to multiple columns. For example, if a data frame has numeric quiz columns named quiz_1, quiz_2, and quiz_3, you could classify each score using the same rules:
quiz_results |>
mutate(across(starts_with("quiz_"), ~ case_when(
is.na(.x) ~ "Missing",
.x >= 80 ~ "High",
.x >= 50 ~ "Pass",
TRUE ~ "Fail"
)))
This changes the selected quiz columns from numeric scores to character labels. Use it only when replacing the numeric values is what you intend. If you need both scores and labels, create separate columns or use a different naming strategy. Learn more in the dplyr across() tutorial.
Example 2: Build a classification and audit unexpected values
When data should fit known ranges, use a fallback label that makes invalid values visible rather than silently grouping them with normal observations.
measurements |>
mutate(reading_status = case_when(
is.na(reading) ~ "Missing",
reading < 0 ~ "Below valid range",
reading > 100 ~ "Above valid range",
reading >= 80 ~ "High",
reading >= 40 ~ "Medium",
TRUE ~ "Low"
))
In this example, the valid range is assumed to be 0–100. The invalid-range rules come before the High and Medium categories so that out-of-range values are not classified as ordinary readings.
Example 3: Use a reusable function for repeated rules
If the same classification rules are used in several places, place them in a small function. This reduces duplication and makes it easier to update the rule consistently.
classify_score <- function(x) {
case_when(
is.na(x) ~ "Unknown",
x >= 80 ~ "High",
x >= 50 ~ "Medium",
TRUE ~ "Low"
)
}
students |>
mutate(score_band = classify_score(score))
This function accepts a numeric vector and returns the corresponding labels. If you change the thresholds later, you can update the function once instead of editing multiple pipelines.
Example 4: Use explicit interval boundaries
For financial or scientific work, explicit boundaries can help document exactly how intervals are defined. This example assigns values to non-overlapping ranges:
data |>
mutate(value_band = case_when(
is.na(value) ~ "Missing",
value < 0 ~ "Negative",
value >= 0 & value < 10 ~ "0 to under 10",
value >= 10 & value < 25 ~ "10 to under 25",
value >= 25 ~ "25 or more"
))
These rules include zero in the first non-negative interval, include 10 in the second interval, and include 25 in the final interval. Defining boundaries carefully avoids accidental gaps or overlaps.
case_when() vs if_else() and base R
Choose the function that makes the logic clearest. case_when() is ideal for several conditions, while if_else() is often simpler for one condition with two possible outcomes.
| Task | dplyr approach | Base R approach |
|---|---|---|
| One TRUE/FALSE condition | if_else(score >= 50, "Pass", "Fail") | ifelse(score >= 50, "Pass", "Fail") |
| Several ordered conditions | case_when(...) | ifelse() nested inside another ifelse(), or indexed assignment |
| Create a column | mutate(band = case_when(...)) | data$band <- ... |
For a single condition, the dplyr version may look like this:
students |>
mutate(result = if_else(score >= 50, "Pass", "Fail"))
For multiple conditions, case_when() is often easier to read than deeply nested ifelse() calls. Note that missing values in the condition need consideration; if_else() supports an explicit missing argument when you want to specify the output for a missing condition.
Common case_when() errors and how to fix them
| Problem | Likely cause | How to fix it |
|---|---|---|
| Unexpected NA results | No condition matched, and no fallback was supplied | Add a suitable final rule such as TRUE ~ "Other", or preserve NA deliberately |
| High values get a lower category | A broad condition appears before a specific one | Put higher thresholds or more specific rules first |
| Missing values are labelled Low | A final TRUE fallback catches missing values too | Add is.na(column) ~ "Unknown" before the other rules |
| Incompatible output types | Different rules return incompatible types, such as numbers and character strings | Return consistent types across all rules |
| Column not found | A misspelled variable name or a column that is not in the data | Check with names(data) and verify spelling and capitalisation |
| Unexpected categories | Thresholds have gaps, overlaps, or incorrect assumptions | Write down boundaries, test edge values, and inspect the results |
Check the result after creating categories
After applying rules, inspect the categories rather than assuming the logic is correct. count() is a quick way to check how many rows fall into each label:
students |>
mutate(grade = case_when(
is.na(score) ~ "Not assessed",
score >= 80 ~ "Excellent",
score >= 50 ~ "Pass",
TRUE ~ "Fail"
)) |>
count(grade)
For larger datasets, also inspect unexpected or missing categories and test values exactly at each boundary, such as 49, 50, 79, and 80.
Practice exercises
Try each exercise before opening the answer. These use the students data frame created at the start of the lesson.
Exercise 1: Label pass and fail
Create a new column called result that labels scores of 50 or more as Pass and lower scores as Fail. Treat a missing score as Unknown.
Show answer
students |>
mutate(result = case_when(
is.na(score) ~ "Unknown",
score >= 50 ~ "Pass",
TRUE ~ "Fail"
))
Exercise 2: Create three performance bands
Label scores of 80 or more as High, scores of 50 to under 80 as Medium, and scores below 50 as Low. Keep missing scores as Unknown.
Show answer
students |>
mutate(band = case_when(
is.na(score) ~ "Unknown",
score >= 80 ~ "High",
score >= 50 ~ "Medium",
TRUE ~ "Low"
))
Exercise 3: Identify students needing support
Flag students whose score is below 50 or whose attendance is below 70. If the score is missing, use Missing score.
Show answer
students |>
mutate(support = case_when(
is.na(score) ~ "Missing score",
score < 50 | attendance < 70 ~ "Needs support",
TRUE ~ "No immediate flag"
))
Exercise 4: Classify attendance
Create an attendance label: High for 90 or more, Moderate for 75 to under 90, and Low for everything else. Treat missing attendance as Unknown.
Show answer
students |>
mutate(attendance_band = case_when(
is.na(attendance) ~ "Unknown",
attendance >= 90 ~ "High",
attendance >= 75 ~ "Moderate",
TRUE ~ "Low"
))
Exercise 5: Count each category
First create the same performance bands as Exercise 2, then count how many students fall into each band.
Show answer
students |>
mutate(band = case_when(
is.na(score) ~ "Unknown",
score >= 80 ~ "High",
score >= 50 ~ "Medium",
TRUE ~ "Low"
)) |>
count(band, sort = TRUE)
dplyr FAQ
What does case_when() do in R?
dplyr case_when() evaluates a series of logical conditions and returns the value associated with the first condition that is TRUE for each observation. It is commonly used inside mutate() to create categories or recode values.
How do I use case_when() in dplyr?
Write each rule as condition ~ result, separate rules with commas, and place the rules inside case_when(). For example, mutate(status = case_when(score >= 50 ~ "Pass", TRUE ~ "Fail")).
Does case_when() use the first matching condition?
Yes. Conditions are checked in order, and the first matching condition supplies the result. Put more specific conditions before broader conditions to avoid a broad rule catching observations too early.
What happens when no case_when() condition is TRUE?
If no condition matches and you do not provide a final fallback rule, case_when() returns a missing value for those observations. Add a final TRUE ~ value when you need a default category.
How do I handle missing values with case_when()?
Test missing values explicitly with is.na(column) before other rules if they need a separate label. For example, is.na(score) ~ "Unknown". Otherwise, unmatched missing values will generally produce a missing result.
What is the difference between if_else() and case_when()?
if_else() is designed for one TRUE/FALSE condition with a true and false result. case_when() is more convenient when you have several conditions or categories.
Can case_when() create a new column?
Yes. Use it inside mutate(), for example data |> mutate(band = case_when(score >= 80 ~ "High", TRUE ~ "Other")). Assign the result to a new data frame if you want to keep it for later use.
Why is case_when() returning NA?
A condition may not match any rule, a source value may be missing, or the conditions may be ordered incorrectly. Check the values, add a fallback such as TRUE ~ "Other", and handle missing values explicitly where appropriate.
Key points to remember
case_when()applies multiple logical rules and returns the result for the first matching condition.- Use
mutate()withcase_when()to create or recode columns. - Write each rule as
condition ~ value, separating rules with commas. - Order matters: put specific conditions before broad ones.
- Add a final
TRUE ~ ...fallback when you want a default for unmatched values. - Use
is.na()to handle missing values explicitly, and ensure every rule returns a compatible type. - Inspect the results with
count()and test values at the edges of each range.
Continue with dplyr across() to apply operations to multiple columns, or revisit mutate() to learn more about creating variables. For grouped summaries after classifying data, see group_by() and summarise().