The Wayback Machine - https://web.archive.org/web/20240909175922/https://www.geeksforgeeks.org/melting-and-casting-in-r-programming/
Open In App

Melting and Casting in R Programming

Last Updated : 12 Jun, 2020
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

Syntax:
melt(data, na.rm = FALSE, value.name = “value”)

Parameters:
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

Example:




# Required library for ships dataset
install.packages("MASS")
  
# Required for melt() and cast() function
install.packages("reshape2")
install.packages("reshape")
  
#Loading the libraries
library(MASS)
library(reshape2)
library(reshape)
  
# Create dataframe
n <- c(1, 1, 2, 2)
time <- c(1, 2, 1, 2)
x <- c(6, 3, 2, 5)
y <- c(1, 4, 6, 9)
df <- data.frame(n, time, x, y)
  
# Original data frame
cat("Original data frame:\n")
print(df)
  
# Organize data w.r.t. n and time
molten.data <- melt(df, id = c("n","time"))
  
cat("\nAfter melting data frame:\n")
print(molten.data)


Output:

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.

Syntax:
cast(data, formula, fun.aggregate)

Parameters:
data: represents dataset
formula: represents the form in which data has to be reshaped
fun.aggregate: represents aggregate function

Example:




# Print recasted dataset using cast() function
cast.data <- cast(molten.data, n~variable, sum)
  
print(cast.data)
  
cat("\n")
time.cast <- cast(molten.data, time~variable, mean)
print(time.cast)


Output:

  n x  y
1 1 9  5
2 2 7 15

  time x   y
1    1 4 3.5
2    2 4 6.5


Similar Reads

What is the Relation Between R Programming and Hadoop Programming?
The relation between R programming and Hadoop revolves around integrating R with the Hadoop ecosystem to analyze large datasets that are stored in a Hadoop environment. R, primarily used for statistical analysis and data visualization, is not inherently built for handling big data. However, when combined with Hadoop, it can leverage Hadoop's distri
3 min read
Compute Variance and Standard Deviation of a value in R Programming - var() and sd() Function
var() function in R Language computes the sample variance of a vector. It is the measure of how much value is away from the mean value. Syntax: var(x) Parameters: x : numeric vector Example 1: Computing variance of a vector # R program to illustrate # variance of vector # Create example vector x &lt;- c(1, 2, 3, 4, 5, 6, 7) # Apply var function in
1 min read
Calculate the Floor and Ceiling values in R Programming - floor() and ceiling() Function
floor() function in R Language returns the largest integer that is smaller than or equal to value passed to it as argument(i.e : rounds downs to the nearest integer). Syntax: floor(x) Parameter: x: Value to be rounded off Example 1: # R program to calculate floor value # Using floor() method answer1 &lt;- floor(1.2) answer2 &lt;- floor(1.5) answer3
1 min read
Naming Rows and Columns of a Matrix in R Programming - rownames() and colnames() Function
rownames() function in R Language is used to set the names to rows of a matrix. Syntax: rownames(x) &lt;- value Parameters: x: Matrix value: Vector of names to be set Example: # R program to provide a name # to rows of a Matrix # Creating a 3X3 Matrix A = matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9), 3, 3, byrow = TRUE) # Calling rownames() Function rowname
1 min read
Get Date and Time in different Formats in R Programming - date(), Sys.Date(), Sys.time() and Sys.timezone() Function
date() function in R Language is used to return the current date and time. Syntax: date() Parameters: Does not accept any parameters Example: # R program to illustrate # date function # Calling date() function to # return current date and time date() Output: [1] "Thu Jun 11 04:29:39 2020" Sys.Date() Function Sys.Date() function is used to return th
1 min read
Compute the Parallel Minima and Maxima between Vectors in R Programming - pmin() and pmax() Functions
pmin() function in R Language is used to return the parallel minima of the input vectors. Syntax: pmin(x1, x2) Parameters: x1: vector one x2: vector two Example 1: # R program to illustrate # pmin() function # First example vector x1 &lt;- c(2, 9, 5, 7, 1, 8) # Second example vector x2 &lt;- c(0, 7, 2, 3, 9, 6) # Application of pmin() in R pmin(x1,
1 min read
Add Leading Zeros to the Elements of a Vector in R Programming - Using paste0() and sprintf() Function
paste0() and sprintf() functions in R Language can also be used to add leading zeros to each element of a vector passed to it as argument. Syntax: paste0("0", vec) or sprintf("%0d", vec)Parameters: paste0: It will add zeros to vector sprintf: To format a vector(adding zeros) vec: Original vector dataReturns: Vectors by addition of leading zeros Exa
1 min read
Absolute and Relative Frequency in R Programming
In statistics, frequency or absolute frequency indicates the number of occurrences of a data value or the number of times a data value occurs. These frequencies are often plotted on bar graphs or histograms to compare the data values. For example, to find out the number of kids, adults, and senior citizens in a particular area, to create a poll on
2 min read
Convert Factor to Numeric and Numeric to Factor in R Programming
Factors are data structures that are implemented to categorize the data or represent categorical data and store it on multiple levels. They can be stored as integers with a corresponding label to every unique integer. Though factors may look similar to character vectors, they are integers, and care must be taken while using them as strings. The fac
5 min read
Grid and Lattice Packages in R Programming
Every programming language has packages to implement different functions. Many functions are bundled together in a package. To use those functions, installation and loading of these packages are required. In R programming, there are 10, 000 packages in the CRAN repository. Grid and Lattice are some of the packages in R Programming Language which im
3 min read
Logarithmic and Power Functions in R Programming
Logarithm and Power are two very important mathematical functions that help in the calculation of data that is growing exponentially with time. First is the Logarithm, to which the general way to calculate the logarithm of the value in the base is with the log() function which takes two arguments as value and base, by default it computes the natura
3 min read
Check if values in a vector are True or not in R Programming - all() and any() Function
In this article, we are going to check if the values in a vector are true or not in R Programming Language. R - all() function all() function in R Language will check in a vector whether all the values are true or not. Syntax: all(x, na.rm) Parameters: x: vectorna.rm: logical, if NA value to removed before result Example 1: Basic example of all() f
2 min read
Return an Object with the specified name in R Programming - get0() and mget() Function
In R programming, get0() and mget() function works similar to get() function. It is used to search and return the object with the specified name passed to it as argument. get0() Function get0() function has the same syntax as get() function but there is an addition of a new parameter which returns an output if the data object is not found. Clearly,
2 min read
Evaluating an Expression in R Programming - with() and within() Function
with() function in R programming evaluates the expression in an environment constructed locally by the data and does not create a copy of the data. Syntax: with(data, expr) Parameters: data represents dataset to be used expr represents formula or expression to be evaluated Example 1: # Creating list df &lt;- list(&quot;x1&quot; = c(1, 2, 3), &quot;
2 min read
Create Matrix and Data Frame from Lists in R Programming
In R programming, there 5 basic objects. Lists are the objects that can contain heterogeneous types of elements, unlike vectors. Matrices can contain the same type of elements or homogeneous elements. On the other hand, data frames are similar to matrices but have an advantage over matrices to keep heterogeneous elements. In this article, we'll lea
3 min read
Performing Logarithmic Computations in R Programming - log(), log10(), log1p(), and log2() Functions
log() function in R Language returns the natural logarithm (base-e logarithm) of the argument passed in the parameter. Syntax: log(x) Parameter: x: Specified value. Returns: It returns the natural logarithm of the specified value, infinity for 0 and NaN for the negative value. Example 1: # R program to calculate log value print(log(1)) print(log(30
3 min read
Check if the elements of a Vector are Finite, Infinite or NaN values in R Programming - is.finite(), is.infinite() and is.nan() Function
is.finite() function in R Language is used to check if the elements of a vector are Finite values or not. It returns a boolean value for all the elements of the vector. Syntax: is.finite(x) Parameters: x: Vector to be checked Example: # R program to illustrate # the use of is.finite() function # Creating a vector x &lt;- c(1, 2, 3, 4, 5, NA, 6, 7)
2 min read
Search and Return an Object with the specified name in R Programming - get() Function
get() function in R Language is used to return an object with the name specified as argument to the function. This is another method of printing values of the objects just like print function. This function can also be used to copy one object to another. Syntax: get(object) Parameters: object: Vector, array, list, etc. Example 1: # R program to ill
1 min read
Get the Minimum and Maximum element of a Vector in R Programming - range() Function
range() function in R Programming Language is used to get the minimum and maximum values of the vector passed to it as an argument. Syntax: range(x, na.rm, finite) Parameters: x: Numeric Vectorna.rm: Boolean value to remove NAfinite: Boolean value to exclude non-finite elementsR - range() Function ExamplesExample 1: Get the Minimum and Maximum elem
1 min read
Search the Interval for Minimum and Maximum of the Function in R Programming - optimize() Function
optimize() or optimise() function in R Language is used to search the interval from lower to upper for a minimum or maximum of the function f with respect to its first argument. Syntax: optimize(f, interval, maximum)Parameters: f: the function to be optimized. The function is either minimized or maximized over its first argument depending on the va
2 min read
Differences Between MATLAB and R Programming Language
MATLAB: MATLAB stands for Matrix Laboratory. MATLAB is a high performance language, initially intended to provide access to the matrix software designed by the projects LINPACK (Linear System Package) and EISPACK (Eigen System Package). It incorporates the environment for computation, visualization and programming. MATLAB provides a modern language
4 min read
Evaluate and Quote an Expression in R Programming - bquote() Function
bquote() function in R Language is used to quote the arguments passed to it, except the values which are wrapped in '.()'. It evaluates the wrapped values and quotes the result. Syntax: bquote(expr) Parameters: expr: language object Example 1: # R program to quote an expression # Assigning value to variable x &lt;- 10 # Calling bquote() Function bq
1 min read
Parsing Date and Time in R Programming - strptime() Function
strptime() function in R Language is used to parse the given representation of date and time with the given template. Syntax: strptime(x, format, tz = "")Parameters: x: given representation of date and time y: given template in which parsing is done tz: a character string specifying the time zone to be used for the conversion Example 1: C/C++ Code
1 min read
Getting String Representation of the given Date and Time Object in R Programming - strftime() Function
strftime() function in R Language is used to convert the given date and time objects to their string representation. Syntax: strftime(time) Parameters: time: specified time object Example 1: C/C++ Code # R program to illustrate # strftime function # Specifying a date and time x &lt;- &quot;2020-06-01 16:15:10 EST&quot; # Calling strftime() function
1 min read
Formatting Numbers and Strings in R Programming - format() Function
Formatting in R can be formatted into the necessary representations using the flexible R function format(). It can be used with many different types of objects, including character strings, date/time data, and numeric numbers. By providing formatting options, the function enables us to regulate how the result looks. The format() function lets us fo
3 min read
Find Eigenvalues and Eigenvectors of a Matrix in R Programming - eigen() Function
eigen() function in R Language is used to calculate eigenvalues and eigenvectors of a matrix. Eigenvalue is the factor by which a eigenvector is scaled. Syntax: eigen(x) Parameters: x: Matrix Example 1: # R program to illustrate # Eigenvalues and eigenvectors of matrix # Create a 3x3 matrix A = matrix(c(1:9), 3, 3) cat(&quot;The 3x3 matrix:\n&quot;
1 min read
Compute Beta Distribution in R Programming - dbeta(), pbeta(), qbeta(), and rbeta() Functions
Beta Distribution in R Language is defined as property which represents the possible values of probability. This article is an illustration of dbeta, pbeta, qbeta, and rbeta functions of Beta Distribution. dbeta() Function It is defined as Beta Density function and is used to create beta density value corresponding to the vector of quantiles. Synta
2 min read
Decision Making in R Programming - if, if-else, if-else-if ladder, nested if-else, and switch
Decision making is about deciding the order of execution of statements based on certain conditions. In decision making programmer needs to provide some condition which is evaluated by the program, along with it there also provided some statements which are executed if the condition is true and optionally other statements if the condition is evaluat
5 min read
Compute Derivative of an Expression in R Programming - deriv() and D() Function
In R programming, derivative of a function can be computed using deriv() and D() function. It is used to compute derivatives of simple expressions. Syntax: deriv(expr, name) D(expr, name) Parameters: expr: represents an expression or a formula with no LHS name: represents character vector to which derivatives will be computed Example 1: # Expressio
1 min read
Set Aspect Ratio of Scatter Plot and Bar Plot in R Programming - Using asp in plot() Function
asp is a parameter of the plot() function in R Language is used to set aspect ratio of plots (Scatterplot and Barplot). Aspect ratio is defined as proportional relationship between width and height of the plot axes. Syntax: plot(x, y, asp ) Parameters: x, y: Coordinates of x and y axis asp: Aspect ratio Example 1: # Set seed for reproducibility set
1 min read
Article Tags :