How to use melt method In R Language

The reshape2 package in R can be used to change the structure of the data supplied and can be installed and imported into the working space using the following command : 

install.packages("reshape2")
library(reshape2)

The melt method in this package can be used to stack data frame columns together. It is used to reshape and elongate the data frame. The melt() method has the following syntax : 

melt(data, id.var , variable.name)

Arguments : 

  • data – The data frame to stack columns of
  • id.ar – The columns to use as primary key
  • variable.name – The new column name to append

Original Data Frame looks as:

    col1 semester quiz_sst quiz_maths
1    Yash        A        1          2
2    Yash        B        3          4
3 Mallika        A        4          6
4 Mallika        B        8          2
5  Muskan        A        9          7
6  Muskan        B        1          3

R




# importing the required library
library("reshape2")
  
# creating a data frame
data <- data.frame(col1=c('Yash', 'Yash', 'Mallika'
                          'Mallika', 'Muskan', 'Muskan'),
                   semester=c(rep(LETTERS[1:2],3)),
                   quiz_sst=c(1, 3, 4, 8, 9, 1),
                   quiz_maths=c(2, 4, 6, 2, 7, 3))
  
# binding the first two columns as it is 
# and stacking the third and fourth columns
data_mod <- reshape2::melt(data, id.var = c('col1', 'semester'),
                           variable.name = 'quiz_marks')
print(data_mod)


Output

[1] "Modified DataFrame"
     col1 semester quiz_marks value
1     Yash        A   quiz_sst     1
2     Yash        B   quiz_sst     3
3  Mallika        A   quiz_sst     4
4  Mallika        B   quiz_sst     8
5   Muskan        A   quiz_sst     9
6   Muskan        B   quiz_sst     1
7     Yash        A quiz_maths     2
8     Yash        B quiz_maths     4
9  Mallika        A quiz_maths     6
10 Mallika        B quiz_maths     2
11  Muskan        A quiz_maths     7
12  Muskan        B quiz_maths     3


How to Stack DataFrame Columns in R?

A dataframe is a tubular structure composed of rows and columns. The dataframe columns can be stacked together to divide the columns depending on the values contained within them. 

Similar Reads

Method 1: Using stack method

The cbind() operation is used to stack the columns of the data frame together. Initially, the first two columns of the data frame are combined together using the df[1:2]. This is followed by the application of stack() method applied on the last two columns....

Method 2: Using melt method

...

Contact Us