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     Northeast   Income   4755 
# 4:  New Hampshire     Northeast   Income   4281 
# 5:   Rhode Island     Northeast   Income   4558 
# 6:        Vermont     Northeast   Income   3907 
# 7:     New Jersey     Northeast   Income   5237 

We can convert this back into a wide table, simply by using the dcast functionality, as follows:

data.table::dcast(dmelted, State + Region ~ variable, value.var="value") 

Read literally, this means keeping the State and Region columns constant, un-collapsing the column named variable with values corresponding to the value column.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.14.245