Open In App

Convert a Data Frame into a Molten Form in R Programming – melt() Function

Last Updated : 17 Jun, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

function in R Language is used to combine multiple columns of s Data Frame into a single column.

Syntax: melt(x, na.rm, value.name)

Parameters:
x: data to be melted
na.rm: Boolean value to remove NA
value.name: Setting column names

Example 1:




# R program to reshape data frame
  
# Loading library
library(reshape) 
  
# Creating a data frame
a <- data.frame(id = c("1", "1", "2", "2"), 
                points = c("1", "2", "1", "2"), 
                x1 = c("5", "3", "6", "2"), 
                x2 = c("6", "5", "1", "4")) 
a
  
# Calling melt() Function
m <- melt(a, id = c("id", "points")) 
print(m) 


Output:

  id points x1 x2
1  1      1  5  6
2  1      2  3  5
3  2      1  6  1
4  2      2  2  4
  id points variable value
1  1      1       x1     5
2  1      2       x1     3
3  2      1       x1     6
4  2      2       x1     2
5  1      1       x2     6
6  1      2       x2     5
7  2      1       x2     1
8  2      2       x2     4

Example 2:




# R program to reshape data frame
  
# Loading library
library(reshape2) 
  
# Calling pre-defined data set
BOD
  
# Calling melt() Function
m <- melt(BOD, variable.name = "Stat", value.name ="Data"
print(m) 


Output:

  Time demand
1    1    8.3
2    2   10.3
3    3   19.0
4    4   16.0
5    5   15.6
6    7   19.8
No id variables; using all as measure variables
     Stat Data
1    Time  1.0
2    Time  2.0
3    Time  3.0
4    Time  4.0
5    Time  5.0
6    Time  7.0
7  demand  8.3
8  demand 10.3
9  demand 19.0
10 demand 16.0
11 demand 15.6
12 demand 19.8


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads