Reshaping, melting, and pivoting data

In this final subsection, we will show how to perform another very common operation quickly and efficiently in data.table. This operation has many names—pivot-table-ing, reshaping, melting/casting, spreading/gathering, converting from long to wide (or vice-versa). But while the nomenclature, I admit, can get pretty complicated, understanding the concept doesn’t have to be! The best first step to explaining this is by the following example:

Here is an example of data that we will, heretofore, refer to as in long format:

     year themonth   N 1: 2016      Sep 225 2: 2016      Aug 215 3: 2016      Jul 411 4: 2016      Jun 169 5: 2016      May 478 ---                 103: 2008      Feb 984104: 2008      Jan 877105: 2016      Mar 360106: 2016      Oct 258107: 2016 Nov 124 ...

Get Data Analysis with R - Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.