CodexBloom - Programming Q&A Platform

scenarios in using `dplyr::mutate()` with complex conditions for creating new columns

👀 Views: 0 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-27
r dplyr data-manipulation R

I'm wondering if anyone has experience with I'm prototyping a solution and I'm trying to create a new column in my data frame based on multiple conditions using `dplyr::mutate()`, but I keep running into issues with unexpected results... Here's my code: ```r library(dplyr) # Sample data frame my_data <- data.frame( id = 1:5, score = c(50, 70, 85, 90, 60), status = c('low', 'medium', 'medium', 'high', 'low') ) # Attempting to create a new column 'grade' my_data <- my_data %>% mutate(grade = case_when( score < 60 ~ 'F', score >= 60 & score < 80 ~ 'C', score >= 80 & status == 'high' ~ 'A', TRUE ~ 'B' )) ``` After running this, I expect the `grade` column to properly reflect the conditions but it seems to return unexpected values. For example, the last entry with a score of 60 and a status of 'low' should be a 'C' but instead, it shows as 'B'. I'm not sure if I'm misusing `case_when()` or if there's something else at play here. I've also tried simplifying the conditions, but I keep getting similar unexpected results. I'm using R version 4.1.0 and `dplyr` version 1.0.7. Any thoughts on how I can resolve this scenario and ensure the grading logic works as intended? What would be the recommended way to handle this?