![]() |
In this article, we will discuss what is Melt Function and how it works in R Programming Language. Melt Function In RIn 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", ...)
Consider a data frame df containing information about students’ test scores in different subjects:
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:
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.
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 ConclusionThe melt() function in R is a valuable tool for reshaping data frames from a wide format to a long format. By specifying the appropriate parameters, you can control which columns remain unchanged and which columns are melted, resulting in a more structured and tidy data format suitable for various analytical tasks. |
Reffered: https://www.geeksforgeeks.org
R Language |
Related |
---|
![]() |
![]() |
![]() |
![]() |
![]() |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 15 |