Hello, readers! In this article, we would be having a look at an important concept of R programming - Reshaping data using R melt() and cast() functions, in detail.
The R melt() and cast() functions help us to reshape the data within a data frame into any customized shape.
Let’s understand both the functions in detail. Here we go!
The melt() function
in R programming is an in-built function. It enables us to reshape and elongate the data frames in a user-defined manner. It organizes the data values in a long data frame format.
Have a look at the below syntax!
Syntax:
We pass the data frame to the reshaped to the function along with na.rm = FALSE as the default value which means the NA values won’t be ignored.
Further, we pass the new variable/column name to value.name parameter to store the elongated values obtained from the function into it.
The ID parameter is set to the column names of the data frame with respect to which the reshaping would happen.
Example:
In this example, we would be making use of libraries ‘MASS, reshape2, and reshape’. Having created the data frame, we apply the melt() function on the data frame with respect to the column A and B.
Output:
As seen above, after applying melt() function, the data frame gets converted to an elongated data frame. In order to regain the nearly original and natural shape of the data frame, R cast() function
is used.
The cast() function accepts an aggregated function and a formula as a parameter (here, formula is the manner in which the data is to be represented after reshaping) and casts the elongated or molted data frame into a nearly aggregated form of data frame.
Syntax:
We can provide the cast() function with any aggregate function available such as mean, sum, etc.
Example:
As seen above, we have passed mean as the aggregate function to cast() and have set variable equivalent to A variable as the format of representation.
Output:
By this, we have come to the end of this topic. Feel free to comment below, in case you come across any question.
Till then, Happy Learning!! :)
Reference:
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.