Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

R- Mutate is not mutating all values

I am trying to see if there is a way I can combine lines of code when mutating multiple values based on another value. However, when I use c() as a list, not all values are mutating, only some. Is there something else I need to do, or do I need to have each mutate on an individual line?

Example data:

Category <- c("Additional Fees", "Additional Fees", "None", "None", "Package", "None")
Item <- c("20oz Upgrade", "Ice Cream", "20oz Upgrade", "Ice Cream", "Ice Cream", "20oz Upgrade")
df <- data.frame(Category, Item)

Longer code that works

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

df2 <- df %>% 
  mutate(Category = ifelse(Item == "20oz Upgrade", "Additional Fees", Category)) %>% 
  mutate(Category = ifelse(Item == "Ice Cream", "Additional Fees", Category))

Combining mutate- but not all values are mutating- I would like to use this though (lines 5 and 6 of Category are not mutating for me).

df1 <- df %>% 
  mutate(Category = ifelse(Item == c("20oz Upgrade", "Ice Cream"), "Additional Fees", Category))

>Solution :

You’ll want to use %in% rather than == because you’re checking if an item is in a vector of two rather than is equal too:

df |> mutate(Category = ifelse(Item %in% c("20oz Upgrade", "Ice Cream"), "Additional Fees", Category))

Output:

         Category         Item
1 Additional Fees 20oz Upgrade
2 Additional Fees    Ice Cream
3 Additional Fees 20oz Upgrade
4 Additional Fees    Ice Cream
5 Additional Fees    Ice Cream
6 Additional Fees 20oz Upgrade
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading