2

How can I go from a table like this:

  ID  Day  car_id value
  1   1    1      0
  1   1    2      4
  1   2    1      1
  1   3    2      0
  2   1    3      0
  2   2    3      2
  2   3    3      0
  ...

To one like this? I have tried using dcast from the package reshape2. It works fine, but as the dataset is quite big, it is a bit slow. Is there another way to do it faster?

  ID  Day  c_id1 c_id2 c_id3 
  1   1    0      4    0   
  1   2    1      0    0
  1   3    0      0    0
  2   1    0      0    0
  2   2    0      0    3
  2   3    0      0    0

Thank you!

RodrigoReis
  • 111
  • 4
  • 3
    Why do you want to reshape? If you are concerned about efficiency I suggest to just avoid reshaping. – Roland Aug 22 '12 at 12:21

2 Answers2

6

The function reshape() in base R is very fast, at the cost of being hard to comprehend what the arguments mean.

reshape(dat, idvar=c("ID", "Day"), timevar="car_id", direction="wide")
  ID Day value.1 value.2 value.3
1  1   1       0       4      NA
3  1   2       1      NA      NA
4  1   3      NA       0      NA
5  2   1      NA      NA       0
6  2   2      NA      NA       2
7  2   3      NA      NA       0
Andrie
  • 176,377
  • 47
  • 447
  • 496
0

An alternative is to use the dcast function from the reshape2 package.

dcast(dat, ID + Day ~ car_id, value.var = 'value')
MadSeb
  • 7,958
  • 21
  • 80
  • 121