Melt Function In R
In data analysis and manipulation, restructuring data is often necessary to facilitate further analysis or visualization. The melt() function in R, provided by the reshape2 or tidyr package, is a powerful tool for reshaping data frames from a wide format to a long format. This article explores the melt() function in detail, discussing its syntax, parameters, and examples to demonstrate its usage.
The basic syntax of the melt() function is as follows:
melt(data, id.vars = NULL, measure.vars = NULL, variable.name = "variable", value.name = "value", ...)
- data: The data frame to be melted.
- id.vars: Names of columns that should remain as identifiers.
- measure.vars: Names of columns to be melted.
- variable.name: The name of the variable column (default is “variable”).
- value.name: The name of the value column (default is “value”).
Consider a data frame df containing information about students’ test scores in different subjects:
# Create a sample data frame
df <- data.frame(
Student = c("John", "Alice", "Bob"),
Math = c(90, 85, 75),
Science = c(80, 92, 88),
History = c(85, 90, 82)
)
# Print the original data frame
print("Original Data Frame:")
print(df)
Output:
[1] "Original Data Frame:"
Student Math Science History
1 John 90 80 85
2 Alice 85 92 90
3 Bob 75 88 82
Now, let’s melt the data frame to convert it from a wide format to a long format:
# Load the reshape2 package
library(reshape2)
# Melt the data frame
melted_df <- melt(df, id.vars = "Student", variable.name = "Subject",
value.name = "Score")
# Print the melted data frame
print("Melted Data Frame:")
print(melted_df)
Output:
[1] "Melted Data Frame:"
Student Subject Score
1 John Math 90
2 Alice Math 85
3 Bob Math 75
4 John Science 80
5 Alice Science 92
6 Bob Science 88
7 John History 85
8 Alice History 90
9 Bob History 82
In the melted data frame, each row represents a unique combination of student, subject, and score, making it easier to analyze or visualize the data.
# Load the reshape2 package
library(reshape2)
# Create a sample data frame
data <- data.frame(
ID = 1:3,
Age = c(25, 30, 35),
Height = c(160, 170, 180),
Weight = c(60, 70, 80)
)
# Print the original data frame
print("Original data:")
print(data)
# Melt the data frame
melted_data <- melt(data, id.vars = "ID")
# Print the melted data frame
print("Melted data:")
print(melted_data)
Output:
[1] "Original data:"
ID Age Height Weight
1 1 25 160 60
2 2 30 170 70
3 3 35 180 80
[1] "Melted data:"
ID variable value
1 1 Age 25
2 2 Age 30
3 3 Age 35
4 1 Height 160
5 2 Height 170
6 3 Height 180
7 1 Weight 60
8 2 Weight 70
9 3 Weight 80
Melt Function In R
In this article, we will discuss what is Melt Function and how it works in R Programming Language.