CodexBloom - Programming Q&A Platform

implementing using `dplyr::mutate()` to create new columns based on conditions in R

👀 Views: 78 đŸ’Ŧ Answers: 1 📅 Created: 2025-07-22
r dplyr dataframe R

I'm a bit lost with I'm trying to create a new column in my data frame using `dplyr::mutate()`, where the values are based on conditions from existing columns... However, I'm working with unexpected results when applying multiple conditions. Here's a simplified example of what I have: ```r library(dplyr) # Sample data frame df <- data.frame( id = 1:5, value = c(10, 20, 30, 40, 50), category = c('A', 'B', 'A', 'B', 'A') ) # Attempting to create a new column based on conditions df <- df %>% mutate( status = case_when( value < 20 ~ 'Low', value >= 20 & value < 40 ~ 'Medium', TRUE ~ 'High' ) ) print(df) ``` When I run this code, I expect the `status` column to reflect 'Low', 'Medium', and 'High' based on the `value` column. However, I noticed that the `status` column is only filled with 'Medium' and 'High', and I'm not getting any 'Low' values at all. The output I received was: ``` id value category status 1 1 10 A Medium 2 2 20 B Medium 3 3 30 A High 4 4 40 B High 5 5 50 A High ``` I tried modifying the conditions and even checking for other factors in the data frame, but nothing seems to work. I'm using R version 4.2.1 and `dplyr` version 1.0.7. Is there a specific reason why the condition for 'Low' is not being met, or could there be an scenario with how I'm using `case_when()`? Any insights would be greatly appreciated. What am I doing wrong? Am I approaching this the right way?