RodrigoReis
RodrigoReis

Reputation: 111

Performance of reshaping table

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!

Upvotes: 2

Views: 541

Answers (2)

MadSeb
MadSeb

Reputation: 8234

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

dcast(dat, ID + Day ~ car_id, value.var = 'value')

Upvotes: 0

Andrie
Andrie

Reputation: 179448

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

Upvotes: 6

Related Questions