Let's say we have non definite number of products in our dataframe (More than three). We can use separate_rows()
from tidyverse
without issues about the number of products and then reshape to wide. Here the code with data you shared (I added more items to see this approach). Here the code:
library(tidyverse)
#Data
df <- structure(list(id = c(1001, 1002, 1003), products = c("milk, cheese, sugar, rice, soap, water",
"milk", "cheese, eggs")), row.names = c(NA, -3L), class = "data.frame")
The code:
#Code
df %>% separate_rows(products,sep = ', ') %>%
group_by(id) %>%
mutate(Var=paste0('V',1:n())) %>%
pivot_wider(names_from = Var,values_from=products) %>%
replace(is.na(.),'')
Output:
# A tibble: 3 x 7
# Groups: id [3]
id V1 V2 V3 V4 V5 V6
<dbl> <chr> <chr> <chr> <chr> <chr> <chr>
1 1001 milk "cheese" "sugar" "rice" "soap" "water"
2 1002 milk "" "" "" "" ""
3 1003 cheese "eggs" "" "" "" ""