I have a dataframe with and id column and an eats column, and a separate food list. I want to process the dataframe so that a column is added for each food in the food list which is populated with 1 if the food is present in eats and 0 otherwise.
txt <- tibble(id = c(1, 2, 3),
eats = c("apple, oats, banana, milk, sugar",
"oats, banana, sugar",
"chocolate, milk, sugar"))
food_list <- c("apple", "oats", "chocolate")
for (i in food_list){
print(i)
txt <- txt %>%
mutate(!!i := if_else(stringr::str_detect(eats, i), 1, 0))
}
I could do this using a for loop but struggling to do it without a loop. I Will be very grateful if someone can point me to how this can be done without using for loops and instead using the purrr library map functions.
Thanks!