0

I have a data frame A which looks like this: there are multiply recurring ID's

ID    |  shopping list
1     |  carrot
1     |  milk
1     |  apple
2     |  milk
2     |  chicken
3     |  milk
4     |  carrot

and I want to get a data frame B: where there are only unique ID values and all shopping list products have their own column. If an ID has a certain product on their shopping list the value is 1 and if it's not the value is 0 for that item.

ID    |  milk | carrot | apple | chicken
1     |  1    | 1      | 1     | 0
2     |  1    | 0      | 0     | 1
3     |  1    | 0      | 0     | 0
4     |  0    | 1      | 0     | 0
r2evans
  • 141,215
  • 6
  • 77
  • 149
pnd123
  • 1
  • Before using `pivot_wider` or `dcast` (from the dupe link), you'll likely want to add a dummy column with the value `1`, then use the `value_fill=` or `fill=` arguments (respectively) to fill the remaining with `0`s. – r2evans Jul 07 '22 at 11:21
  • For instance, `dat$a <- 1`, then either `tidyr::pivot_wider(dat, ID, names_from="shopping_list", values_from="a", values_fill=list(a=0))` or `reshape2::dcast(dat, ID ~ shopping_list, value.var = "a", fill = 0)`, both work. – r2evans Jul 07 '22 at 11:22

0 Answers0