CodexBloom - Programming Q&A Platform

how to achieve desired row-wise operation with dplyr's mutate and ifelse in R

šŸ‘€ Views: 0 šŸ’¬ Answers: 1 šŸ“… Created: 2025-08-29
r dplyr mutate R

I'm relatively new to this, so bear with me. I'm trying to create a new column in my data frame based on a condition applied row-wise using `dplyr`. My goal is to assign a value based on whether another column exceeds a certain threshold. However, I'm working with unexpected behavior where the new column is filled with `NA` values instead of the calculated values. Here's what I've tried so far: ```r library(dplyr) # Sample data frame my_data <- data.frame( id = 1:4, score = c(80, 95, 70, 85) ) # Attempting to create a new column 'result' based on 'score' my_data <- my_data %>% mutate(result = ifelse(score > 90, "Excellent", "Needs Improvement")) ``` When I run the above code, I expect the `result` column to show "Needs Improvement" for the first three rows and "Excellent" for the fourth. Instead, when I check `my_data`, the `result` column contains `NA` values in all rows. I've ensured that the `score` column is numeric and there are no missing values in it. I've also tried using the base R approach with `ifelse()` directly and it gives the same result: ```r my_data$result <- ifelse(my_data$score > 90, "Excellent", "Needs Improvement") ``` Is there something I'm missing in the implementation of `mutate()` or `ifelse()`? I’m using R version 4.1.0 and dplyr version 1.0.7. Any help would be greatly appreciated! I'm working on a web app that needs to handle this. What's the best practice here?