Hello!
I have a data set with lots of character categories. I am trying to create a new character column based on groupings of character values from one of the columns.
In the example code below I am trying to group different character values in the " Food Types" column into a new column called "Food Category" with an appropriate character category.
For example "broccoli", "grapes", "apple bananas" are all to have an associated "Food Category" label of "fruit and veg" while "coke (diet)" and "juice" will have a Food Category label of "beverage choices" and so on.
I tried using case_when below and it DOES NOT work because I'm using character strings. How can I group these variables in the column "Food Types" to display the appropriate label in a new "Food Category" column.
Thank you!
NOTE: I purposefully made variables and observations to both have spaces in the names as that mirrors the type of data I am working with and the spaces need to be preserved. It also has posed an extra layer of frustration.
`Food types` <- c("candy bar", "pizza pie", "coke (diet)", "broccoli", "grapes", "apple bananas", "juice")
`super market` <-rep(c("WF", "TJ", "Luckies"), each = 7)
d <- cbind(`Food types`, `super market`)
df <- as.data.frame(d)
df %>% mutate("Food Category" =
case_when(
`Food types` =
"candy bar" ~ "junk food",
`Food types` =
c("coke (diet)", "juice") ~ "beverage choices"
`Food types` =
c("broccoli", "grapes", "apple bananas") ~ "fruit and veg",
`Food types` =
"pizza pie" ~ "other foods"))