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)]