R Language Pivot and unpivot with data.table


  • Melt with melt(DT, id.vars=c(..), variable.name="CategoryLabel", value.name="Value")
  • Cast with dcast(DT, LHS ~ RHS, value.var="Value", fun.aggregate=sum)


id.varstell melt which columns to retain
variable.nametell melt what to call the column with category labels
value.nametell melt what to call the column that has values associated with category labels
value.vartell dcast where to find the values to cast in columns
formulatell dcast which columns to retain to form a unique record identifier (LHS) and which one holds the category labels (RHS)
fun.aggregatespecify the function to use when the casting operation generates a list of values in each cell


Much of what goes into conditioning data to build models or visualizations can be accomplished with data.table. As compare to other options, data.table offers advantages of speed and flexibility.