-1

I have a the following data frame:

>dta
    ids names
1 1001    P1
2 1001    P2
3 1002    P1
4 1003    P2
5 1003    P3
6 1003    P4
7 1004    P1

I want to structure the above set in the following format:

  ids V1 V2 V3
1 1001 P1 P2   
2 1002 P1      
3 1003 P2 P3 P4
4 1004 P1      

Please suggest the codes to achieve this. Thanks

Anurag H
  • 909
  • 11
  • 28
  • Is [Transposing Long to Wide without Timevar (or with if it works!)](http://stackoverflow.com/questions/11322801/transposing-long-to-wide-without-timevar-or-with-if-it-works) the canonical duplicate for "`reshape`/`dcast`, but first we must create an id/timevar variable"? – Henrik Mar 17 '16 at 16:01
  • Thanks Henrik, akrun's solution worked for me – Anurag H Mar 17 '16 at 16:19

1 Answers1

1

We can create a sequence column and then use dcast from reshape or data.table (for faster conversion). The sequence column can also be created with ave or other group by options. But, here I used the convenient function getanID from splitstackshape.

library(splitstackshape)
library(reshape2)
dcast(getanID(dta, 'ids'), ids~ paste0("V", .id), 
             value.var='names', fill='')
#  ids V1 V2 V3
#1: 1001 P1 P2   
#2: 1002 P1      
#3: 1003 P2 P3 P4
#4: 1004 P1      
akrun
  • 874,273
  • 37
  • 540
  • 662