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
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))
CodePudding user response:
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