Get startedGet started for free

Melting data.tables

1. Melting data.tables

In this lesson, you will learn how to melt data tables from wide to long formats.

2. Melting a wide data.table

A wide format data table is one where a single variable is spread across multiple columns corresponding to some grouping, such as in the example data table on the left. This type of layout is common when working with excel spreadsheets because it is a human friendly way of organising data with regular groupings. However, when working with datasets in R, you will often want to reshape this data into a long format, shown on the right. In the long format these values occupy a single column, with another column indicating group membership. This format allows you to take full advantage of the functionality in the data table syntax like grouping of calculations.

3. The `melt()` function

You can use the melt() function to reshape a wide data table to a long data table. There are a few different ways you can use this function. First, you can provide a vector of column names to the measure dot vars argument. The melt() function will take these columns and stack them on top of each other to create two new columns: "variable" and "value". The "value" column will contain the values of these stacked columns while the "variable" column labels each row with the column name from the original wide data table.

4. The `melt()` function

You can give these new columns any name you like using the variable dot name and value dot name arguments.

5. The `melt()` function

You can also use the id dot vars argument instead of the measure dot vars argument to tell the melt() function which columns you want to keep aside as row identifiers in the new data table. The melt() function will then stack all other columns into the new "value" column.

6. The `melt()` function

You can use both the id dot vars and measure dot vars arguments at the same time. If you use both arguments, any columns you don't provide to either argument will be dropped in the result.

7. Let's practice!

Now it's your turn to see how melt() works in practice.