Melting and Casting are one of the interesting aspects in R programming to change the shape of the data and further, getting the desired shape. R programming language has many methods to reshape the data using reshape package. melt() and cast() are the functions that efficiently reshape the data. There are many packages in R that require data reshaping. Each data is specified in multiple rows of dataframe with different details in each row and this type of format of data is known as long format.
Melting in R
Melting in R programming is done to organize the data. It is performed using melt() function which takes dataset and column values that has to be kept constant. Using melt(), dataframe is converted into long format and stretches the data frame.
melt(data, na.rm = FALSE, value.name = “value”)
data: represents dataset that has to be reshaped
na.rm: if TRUE, removes NA values from dataset
value.name: represents name of variable used to store values
Original data frame: n time x y 1 1 1 6 1 2 1 2 3 4 3 2 1 2 6 4 2 2 5 9 After melting data frame: n time variable value 1 1 1 x 6 2 1 2 x 3 3 2 1 x 2 4 2 2 x 5 5 1 1 y 1 6 1 2 y 4 7 2 1 y 6 8 2 2 y 9
Casting in R
Casting in R programming is used to reshape the molten data using cast() function which takes aggregate function and formula to aggregate the data accordingly. This function is used to convert long format data back into some aggregated form of data based on the formula in the cast() function.
cast(data, formula, fun.aggregate)
data: represents dataset
formula: represents the form in which data has to be reshaped
fun.aggregate: represents aggregate function
n x y 1 1 9 5 2 2 7 15 time x y 1 1 4 3.5 2 2 4 6.5
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.