The melt functionality

The data.table::melt function is used to convert a wide table into a long table, that is, the columns are collapsed into a key and value relationship.

If, say, we wanted to convert the dstate table into a long table consisting of a column with StateRegionIncome, and Area as the values, we could use:

dmelted <- data.table::melt(dstate, id.vars=c("State","Region"), measure.vars=c("Income","Area")) 
dmelted  

An easy way to remember this is that id.vars are the columns that will remain constant, in this case, StateRegion, and measure.vars indicate the columns that will be collapsed as shown as follows:

# State Region variable value # 1: Connecticut Northeast Income 5348 # 2: Maine Northeast Income 3694 # 3: Massachusetts ...

Get Hands-On Data Science with R now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.