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

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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) 

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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) 

chevron_right


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



My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.