1

I'm wondering whether my two step solution can be reduced to one melt() call or done more simply somehow using data.table.

My data:

DT <- data.table(category = c("x", "y"), `2010` = c(10, 20), `2011` = c(40, 43))
DT # Has much more columns in reality
   category 2010 2011
1:        x   10   40
2:        y   20   43

Expected output:

   year  x  y
1: 2010 10 20
2: 2011 40 43

Current solution:

library(data.table)

melt(DT, id.vars = "category", variable.name = "year")[, dcast(.SD, year ~ category)]
s_baldur
  • 29,441
  • 4
  • 36
  • 69

2 Answers2

2

It can be done with recast (wrapper for melt/dcast)

library(reshape2)
recast(DT, variable ~ category, id.var = 'category')
akrun
  • 874,273
  • 37
  • 540
  • 662
2

Using data.table version >= 1.12.4, you can use transpose as follows for this particular case:

transpose(DT, keep.names="year", make.names="category")

output:

   year  x  y
1: 2010 10 20
2: 2011 40 43
chinsoon12
  • 25,005
  • 4
  • 25
  • 35