Home » How to Use the melt() Function in R

How to Use the melt() Function in R

by Tutor Aspire

You can use the melt() function from the reshape2 package in R to convert a data frame from a wide format to a long format.

A wide format contains values that do not repeat in the first column.

A long format contains values that do repeat in the first column.

For example, consider the following two datasets that contain the exact same data expressed in different formats:

Wide vs. Long Data Format

The melt() function uses the following basic syntax to convert a data frame in a wide format to a long format:

melt(df, id='team')

The id argument specifies which variable to use as the first column in the data frame whose values will be repeated.

The following example shows how to use this function in practice.

Example: How to Use melt() in R

Suppose we have the following data frame in R that is currently in a wide format:

#create data frame in wide format
df frame(team=c('A', 'B', 'C', 'D'),
                 points=c(88, 91, 99, 94),
                 assists=c(12, 17, 24, 28),
                 rebounds=c(22, 28, 30, 31))

#view data frame
df

  team points assists rebounds
1    A     88      12       22
2    B     91      17       28
3    C     99      24       30
4    D     94      28       31

We can use the melt() function to quickly convert the data frame to a long format:

library(reshape2)

#use melt() to convert data frame from wide to long format
long_df team')

#view long data frame
long_df

   team variable value
1     A   points    88
2     B   points    91
3     C   points    99
4     D   points    94
5     A  assists    12
6     B  assists    17
7     C  assists    24
8     D  assists    28
9     A rebounds    22
10    B rebounds    28
11    C rebounds    30
12    D rebounds    31

Notice that the data frame is now in a long format.

The columns points, assists, and rebounds have all been compressed into a single column called variable while their values have all been compressed into a single column called values.

Feel free to rename the columns in the resulting data frame by using the names() function:

#rename columns in long_df
names(long_df) team', 'metric', 'amount')

#view updated data frame
long_df

   team   metric amount
1     A   points     88
2     B   points     91
3     C   points     99
4     D   points     94
5     A  assists     12
6     B  assists     17
7     C  assists     24
8     D  assists     28
9     A rebounds     22
10    B rebounds     28
11    C rebounds     30
12    D rebounds     31

Notice that the columns have been renamed.

Additional Resources

The following tutorials explain how to perform other common tasks in R:

How to Filter Rows in R
How to Transpose a Data Frame in R
How to Rename Data Frame Columns in R

You may also like