I have a 2-column dataframe. First column contains a single entry of a class of items (in this case, vegetables). The second column is the incoming new_item
, which are grocery items of different categories (meat, fruit, veg, etc).
library(tidyverse)
current <- tibble::tribble(
~prev_veg, ~new_item,
"cabbage", "lettuce",
NA, "apple",
NA, "beef",
NA, "spinach",
NA, "broccoli",
NA, "mango"
)
current
I would like to loop through the new item column, and only add vegetables to prev_veg
. Any new item that is vegetable needs to be appended onto the existing list. Importantly, I have a vector of all possible vegetables that could occur in that list. The desired dataframe is below.
target_veg <- c("cabbage","lettuce", "spinach", "broccoli"
desired <- tibble::tribble(
~prev_veg, ~new_item,
"cabbage", "lettuce",
"cabbage, lettuce", "apple",
"cabbage, lettuce", "strawbery",
"cabbage, lettuce", "spinach",
"cabbage, lettuce, spinach", "broccoli",
"cabbage, lettuce, spinach, broccoli", "mango"
)
desired
Finally, there are multiple other data columns in this dataframe that I have not included here (only relevant columns included). Ideally looking for a dplyr solution please.