0

I have the following data that has been sorted:

Id    Items
1      a,b
1       c
2       c
3      a,c
3       d
3       e

I would like to reformat into the following format:

Id    Items1    Items2     Items3
1      a,b        c
2       c          
3      a,c        d          e

Can I use reshape to do this? If yes, how?

tatami
  • 133
  • 1
  • 8

1 Answers1

2

We can use dcast

library(data.table)
dcast(setDT(df1), Id~paste0("Items", rowid(Id)), value.var = "Items", fill = "")
#   Id Items1 Items2 Items3
#1:  1    a,b      c       
#2:  2      c              
#3:  3    a,c      d      e
akrun
  • 874,273
  • 37
  • 540
  • 662
  • For some reason, my R has problem with the the command "rowid". May I know if there are alternative command I can use to replace that? Thanks – tatami Dec 13 '16 at 07:44
  • @tatami It is in the newer versions of `data.table`. i.e. `1.10.0` Can you update your data.table version. – akrun Dec 13 '16 at 08:40