Stats

28 Contributors: 1 Wednesday, September 21, 2016
Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Rip Tutorial: riptutorial@gmail.com
Roadmap: roadmap

Pivot and unpivot with data.table

Syntax

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

Parameters

ParameterDetails
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

Remarks

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.

Related Examples