1

I have a dataframe of transactional data, for example:

ID   TYPE    QUANTITY
01    A    2
01    B    1
01    C    4
02    A    3
02    C    2
03    C    3

I need to split ID by the factors in TYPE and from those factors create new columns that contain the QUANTITY value for each column.

So that it will look like this:

ID    A    B    C
01    2    1    4
02    3    0    2
03    0    0    3
pogibas
  • 27,303
  • 19
  • 84
  • 117
STACKin
  • 45
  • 6

3 Answers3

2

use the tidyr package and make your long format to a wide format

library(tidyr)
spread(df, key = 'TYPE', value= 'QUANTITY')
Linus
  • 705
  • 1
  • 10
  • 20
1

You can use dcast() from reshape2 package.

library(reshape2)
dcast(df, ID ~ TYPE, fun.aggregate = sum)
  ID A B C
1  1 2 1 4
2  2 3 0 2
3  3 0 0 3
pogibas
  • 27,303
  • 19
  • 84
  • 117
0

This is basically using base r

reshape(data,v.names="QUANTITY",timevar = "TYPE",idvar = "ID",direction = "wide")
Onyambu
  • 67,392
  • 3
  • 24
  • 53
  • Although the use of `cast` or `dcast` or `recast` or even `acast` from `reshape` and `reshape2` packages depending on what is needed might be quite easy to follow and manipulate. – Onyambu Dec 22 '17 at 19:18