How can I reshape a data.table when the order of the registers determines the category?

Viewed 87

Let's say I have the following data table:

dt=data.table(type=c('big','medium','small','small'
                     ,'medium','small','small'
                     ,'big','medium','small','small')
             ,category=letters[1:11])

      type category
 1:    big        a
 2: medium        b
 3:  small        c
 4:  small        d
 5: medium        e
 6:  small        f
 7:  small        g
 8:    big        h
 9: medium        i
10:  small        j
11:  small        k

In this case I have a category hierarchy: the 'big' type is the same for all rows until a following 'big' type is seen. And the behavior is the same for every type.

The reshape I want must give me the following:

dt=data.table(type=c('big','medium','small','small'
                     ,'medium','small','small'
                     ,'big','medium','small','small')
              ,category=letters[1:11])


   big medium small
1:   a      b     c
2:   a      b     d
3:   a      e     f
4:   a      e     g
5:   h      i     j
6:   h      i     k

As you can see each category only changes when a register of the same category is found, the order is important to set this categories.

Do you think there is a way to do this without using a for?

1 Answers
Related