0

I got a data.frame that I want to spread kind of like dplyr's spread function but with more than one variable.

Code    Product 2008    2008_Unit   2015    2015_Unit   Type
010110  Pure-bred breeding horses and asses 1   Tons    NA  NA  Exports_Peru_US
010110  Pure-bred breeding horses and asses 6   Tons    NA  NA  Exports_Peru_World
010110  Pure-bred breeding horses and asses 55  Units   NA  NA  Exports_US_Peru
010110  Pure-bred breeding horses and asses 3899    Units   NA  NA  Exports_US_World
010110  Pure-bred breeding horses and asses 0   No quantity 6   Tons    Exports_World
010110  Pure-bred breeding horses and asses 31  Tons    NA  NA  Imports_Peru_US

I wanna turn this into:

Code    Product 2008_Exports_Peru_US    2008_Unit_Exports_Peru_US   2015_Exports_Peru_US    2015_Unit_Exports_Peru_US   2008_Exports_Peru_World ...
010110  Pure-bred breeding horses and asses 1   Tons    NA  NA  6   ...

So each Code only appears in one row.

Note: Not all of the Codes have all types.

reshape2 + data.table works

dcast(setDT(master), Code + Product ~ Type, value.var = c("2008","2008_Unit", "2015", "2015_Unit"))
GonzaloXavier
  • 128
  • 3
  • 13
  • have you tried `spread` from `dplyr`? – Aramis7d May 01 '17 at 05:50
  • 1
    Possible duplicate of [How can I spread repeated measures of multiple variables into wide format?](http://stackoverflow.com/questions/29775461/how-can-i-spread-repeated-measures-of-multiple-variables-into-wide-format) – Aramis7d May 01 '17 at 05:51
  • @Aramis7d I have, by using many spreads I still end up with multiples of the same Code id. Cannot use one because spread only takes 1 argument and I have 4 columns I need to spread across. I've also tried dcast to no success (Though maybe it's just me being inexperienced with the reshape2 package). – GonzaloXavier May 01 '17 at 05:54
  • Needed data.table along with reshape2 for it to work. Question Solved. – GonzaloXavier May 01 '17 at 06:00

1 Answers1

0

reshape2 + data.table works

master <- the data frame
dcast(setDT(master), Code + Product ~ Type, value.var = c("2008","2008_Unit", "2015", "2015_Unit"))
GonzaloXavier
  • 128
  • 3
  • 13