Reshaping Data with the reshape Package

This paper presents the reshape package for R , which provides a common framework for many types of data reshaping and aggregation. It uses a paradigm of ‘melting’ and ‘casting’, where the data are ‘melted’ into a form which distinguishes measured and identifying variables, and then ‘cast’ into a new shape, whether it be a data frame, list, or high dimensional array. The paper includes an introduction to the conceptual framework, practical advice for melting and casting, and a case study.


Introduction
Reshaping data is a common task in real-life data analysis, and it is usually tedious and frustrating.You've struggled with this task in Excel, in SAS, and in R: how do you get your clients' data into the form that you need for summary and analysis?This paper describes version 0.8.1 of the reshape package for R (R Development Core Team 2007), which presents a new approach that aims to reduce the tedium and complexity of reshaping data.
Data often has multiple levels of grouping (nested treatments, split plot designs, or repeated measurements) and typically requires investigation at multiple levels.For example, from a long term clinical study we may be interested in investigating relationships over time, or between times or patients or treatments.To make your job even more difficult, the data probably has been collected and stored in a way optimised for ease and accuracy of collection, and in no way resembles the form you need for statistical analysis.You need to be able to fluently and fluidly reshape the data to meet your needs, but most software packages make it difficult to generalise these tasks, and new code needs to be written for each new case.
While you are probably familiar with the idea of reshaping, it is useful to be a little more formal.Data reshaping involves a rearrangement of the form, but not the content, of the data.Reshaping is a little like creating a contingency table, as there are many ways to arrange the

Conceptual framework
To help us think about the many ways we might rearrange a data set, it is useful to think about data in a new way.Usually, we think about data in terms of a matrix or data frame, where we have observations in the rows and variables in the columns.For the purposes of reshaping, we can divide the variables into two groups: identifier and measured variables.
1. Identifier (id) variables identify the unit that measurements take place on.Id variables are usually discrete, and are typically fixed by design.In anova notation (Y ijk ), id variables are the indices on the variables (i, j, k); in database notation, id variables are a composite primary key.

Measured variables represent what is measured on that unit (Y ).
It is possible to take this abstraction one step further and say there are only id variables and a value, where the id variables also identify what measured variable the value represents.For example, we could represent this data set, which has two id variables (subject and time): From this form, we can create new forms by specifying which variables should form the columns and rows.In the original data frame, the 'variable' id variable forms the columns, and all identifiers form the rows.We do not have to specify all the original id variables in the new form.When we do not, the combination of id variables will no longer identify one value, but many, and we will aggregate the data as well as reshaping it.The function that reduces these many numbers to one is called an aggregation function.
The following section describes the melting operation in detail, as implemented in the reshape package.

Melting data
Melting a data frame is a little trickier in practice than it is in theory.This section describes the practical use of the melt function in R.
In R, melting is a generic operation that can be applied to different data storage objects including data frames, arrays and matrices.This section describes the most common case, melting a data frame.Reshape also provides support for less common data structures, including high-dimensional arrays and lists of data frames or matrices.The built-in documentation for melt, ?melt, lists all objects that can be melted, and provides links to more details.?melt.data.framedocuments the most common case of melting a data frame.
The melt function needs to know which variables are measured and which are identifiers.This distinction should be obvious from your design: if you fixed the value, it is an id variable.If you do not specify them explicitly, melt will assume that any factor or integer column is an id variable.If you specify only one of measured and identifier variables, melt assumes that all the other variables are the other sort.For example, with the smiths dataset, as shown above, all the following calls have the same effect: R> melt(smiths, id = c("subject", "time"), measured = c("age", "weight", + "height")) R> melt(smiths, id = c("subject", "time")) R> melt(smiths, id = 1:2) R> melt(smiths, measured = c("age", "weight", "height")) R> melt(smiths) If you want to run these functions yourself, the smiths dataset is included in the reshape package.
Melt does not make many assumptions about your measured and id variables: there can be any number, in any order, and the values within the columns can be in any order too.In the current implementation, there is only one assumption that melt makes: all measured values must be of the same type, e.g., numeric, factor, date.We need this assumption because the molten data is stored in a R data frame, and the value column can be only one type.Most of the time this is not a problem as there are few cases where it makes sense to combine different types of variables in the cast output.

Melting data with id variables encoded in column names
A more complicated case is where the variable names contain information about more than one variable.For example, here we have an experiment with two treatments (A and B) with data recorded on two time points (1 and 2), and the column names represent both the treatment and the time at which the measurement was taken.It is important to make these implicit variables explicit as part of the data preparation process, as it ensures all id variables are represented in the same way.
R> trial <-data.frame(id= factor(1:4 To fix this we need to create a time and treatment column after melting: This uses the colsplit function described in ?colsplit, which deals with the simple case where variable names are concatenated together with some separator.In general variable names can be constructed in many different ways and may need a custom regular expression to tease apart multiple components.

Already molten data
Sometimes your data may already be in molten form.In this case, all that is necessary is to ensure that the value column is named 'value'.See ?rename for one way to do this.

Missing values in molten data
Finally, it is important to discuss what happens to missing values when you melt your data.
Explicitly coded missing values usually denote sampling zeros rather than structural missings, which are usually implicit in the data.Clearly a structural missing depends on the structure of the data and as we are changing the structure of the data, we might expect some changes to structural missings.Structural missings change from implicit to explicit when we change from a nested to a crossed structure.For example, imagine a dataset with two id variables, sex (male or female) and pregnant (yes or no).When the variables are nested (ie.both on the same dimension) then the missing value 'pregnant male' is encoded by its absence.However, in a crossed view, we need to add an explicit missing as there will now be a cell which must be filled with something.This is illustrated below: sex pregnant value 1 male no 10 2 female no 14 3 female yes 4 sex no yes 1 female 14 4 2 male 10 In this vein, one way to describe the molten form is that it is perfectly nested: there are no crossings.For this reason, it is possible to encode all missing values implicitly, by omitting that combination of id variables, rather than explicitly, with an NA value.However, you may expect these to be in the data frame, and it is a bad idea for a function to throw data away by default, so you need to explicitly state that implicit missing values are ok.In most cases it is safe to get rid of them, which you can do by using na.rm = TRUE in the call to melt.

Casting molten data
Once you have your data in the molten form, you can use cast to rearrange it into the shape that you want.The cast function has two required arguments: • data: the molten data set to reshape • formula: the casting formula which describes the shape of the output format (if you omit this argument, cast will return the data frame in the classic form with measured variables in the columns, and all other id variables in the rows) Most of this section explains the different casting formulas you can use.It also explains the use of two other optional arguments to cast: • fun.aggregate: aggregation function to use, if necessary • margins: what marginal values should be computed

Basic use
The casting formula has this basic form col_var_1 + col_var_2 ~row_var_1 + row_var_2.This describes which variables you want to appear in the columns and which in the rows.These variables need to come from the molten data frame or be one of the following special variables: • .corresponds to no variable, useful when creating formulas of the form . ~x or x ~., that is, a single row or column.
• ... represents all variables not already included in the casting formula.Including this in your formula will guarantee that no aggregation occurs.There can be only one ... in a cast formula.
• result_variable is used when your aggregation formula returns multiple results.See Section 4.6, page 14, for more details.As illustrated above, the order in which the row and column variables are specified is very important.As with a contingency table, there are many possible ways of displaying the same variables, and the way that they are organised will reveal different patterns in the data.Variables specified first vary slowest, and those specified last vary fastest.Because comparisons are made most easily between adjacent cells, the variable you are most interested in should be specified last, and the early variables should be thought of as conditioning variables.An additional constraint is that displays have limited width but essentially infinite length, so variables with many levels may need to be specified as row variables.

High-dimensional arrays
You can use more than one ~to create structures with more than two dimensions.For example, a cast formula of x ~y ~z will create a 3D array with x, y, and z dimensions.You can also still use multiple variables in each dimension: x + a ~y + b ~z + c.The following example shows the resulting dimensionality of various casting formulas.I do not show the actual output here because it is too large.You may want to verify the results for yourself: The high-dimensional array form is useful for sweeping out margins with sweep, or modifying with iapply (Section 5, page 15).
The ~operator is a type of crossing operator, as all combinations of the variables will appear in the output table.Compare this to the + operator, where only combinations that appear in the data will appear in the output.For this reason, increasing the dimensionality of the output, i.e., using more ~s, will generally increase the number of structural missings.This is illustrated below: Margins of high-dimensional arrays are currently unsupported.

R> cast(ffm
This form is useful for input to lapply and sapply, and completes the discussion of the different types of output you can create with reshape.The remainder of the section discusses aggregation.

Aggregation
Whenever there are fewer cells in the cast form than there were in the original data format, an aggregation function is necessary.This formula reduces multiple cells into one, and is supplied in the fun.aggregate argument, which defaults (with a warning) to length.Aggregation is a very common and useful operation and the case studies section (Section 6, page 16) contains further examples of aggregation.
The aggregation function will be passed the vector of a values for one cell.

Margins
It is often useful to be able to add statistics to the margins of your tables, for example, as suggested by Chatfield (1995).You can tell cast to display all margins with margins = TRUE, or list individual variables in a character vector, margins = c("subject", "day").There are two special margins, "grand_col" and "grand_row", which display margins for the overall columns and rows respectively.Margins are indicated with '(all)' as the value of the variable that was margined over.
These examples illustrate some of the possible ways to use margins.I've used sum as the aggregation function so that you can check the results yourself.Note that changing the order and position of the variables in the cast formula affects the margins that can be computed.

Returning multiple values
Occasionally it is useful to aggregate with a function that returns multiple values, e.g., range or summary.This can be thought of as combining multiple casts each with an aggregation function that returns one variable.To display this we need to add an extra variable, result_variable that differentiates the multiple return values.By default, this new id variable will be shown as the last column variable, but you can specify the position manually by including result_variable in the casting formula.

Other convenience functions
There are many other problems encountered in practical analysis that can be painful to overcome without some handy functions.This section describes some of the functions that reshape provides to make dealing with data a little bit easier.More details are provided in the respective documentation.

Factors
• combine_factor combines levels in a factor.For example, if you have many small levels you can combine them together into an 'other' level.
• reorder_factor reorders a factor based on another variable.For example, you can order a factor by the average value of a variable for each level.

Data frames
• rescaler performs column-wise rescaling of data frames, with a variety of different scaling options including rank, common range and common variance.It automatically preserves non-numeric variables.
• merge.allmerges multiple data frames together, an extension of merge in base R. It assumes that all columns with the same name should be equated.
• rbind.fillrbinds two data frames together, filling in any missing columns in the second data frame with missing values.

Miscellaneous
• round_any allows you to round a number to any degree of accuracy, e.g., to the nearest 1, 10, or any other number.
• iapply is an idempotent version of the apply function.It is idempotent in the sense that iapply(x, a, function(x) x) is guaranteed to return x for any value of a.This is useful when dealing with high-dimensional arrays as it will return the array in the same shape that you sent it.It also supports functions that return matrices or arrays in a sensible manner.
We can also easily see the range of values that each variable takes: R> cast(ffm, variable ~., c(min, max)) variable min max 1 potato 0 14.9 2 buttery 0 11.2 3 grassy 0 11.1 4 rancid 0 14.9 5 painty 0 13.1 Better than just looking at the ranges is to look at the distribution, with a histogram.Here we use the molten data directly, facetting (aka conditioning or trellising) by the measured variable.

Tables of means
When creating these tables, it is a good idea to restrict the number of digits displayed.You can do this globally, by setting options(digits = 2), or locally, by using round_any.
Since the data are fairly well balanced, we can do some (crude) investigation as to the effects of the different treatments.For example, we can calculate the overall means for each sensory attribute for each treatment: R> options(digits = 2) R> cast(ffm, treatment ~variable, mean, margins = c("grand_col", + "grand_row")) treatment potato buttery grassy rancid painty (all) 1 1 6.9 1.8 0.65 4.1 2.6 3.2 2 2 7.0 2.0 0.66 3.6 2.5 3.1 3 3 7.0 1.7 0.68 3.9 2.5 3.2 4 (all) 7.0 1.8 0.66 3.9 2.5 3.2 It does not look like there is any effect of treatment.This could be confirmed using a more formal analysis of variance.

Investigating inter-rep reliability
Since we have a repetition over treatments, we might be interested in how reliable each subject is: are the scores for the two repetitions highly correlated?We can explore this graphically by reshaping the data and plotting the data.Our graphical tools work best when the things we want to compare are in different columns, so we'll cast the data to have a column for each rep.In quality control literature, this is known as a Youden plot (Youden 1959).
The correlation looks strong for potatoey and buttery, and poor for rancid and painty.Grassy has many low values, particularly zeros, as seen in the histogram.This reflects the training the participants received for the trial: they were trained to taste potato and buttery flavours, their grassy reference flavour was parsley (very grassy compared to French fries), and they were not trained on rancid or painty flavours.
If we wanted to explore the relationships between subjects or times or treatments we could follow similar steps.

Where to go next
You can find a quick reference and more examples in ?melt and ?cast.You can find some additional information on the reshape website http://had.co.nz/reshape/, including copies of presentations and papers related to reshape.
I would like to include more case studies of reshape in use.If you have an interesting example, or there is something you are struggling with please let me know: h.wickham@gmail.com.
now represents one observation of one variable.This operation is called melting and produces 'molten' data.Compared to the original data set, the molten data has a new id variable 'variable', and a new column 'value', which represents the value of that observation.We now have the data in a form in which there are only id variables and a value.
The two different results are illustrated below.
If you do not use na.rm = TRUE you will need to make sure to account for possible missing values when aggregating (Section 4.4, page 11), for example, by supplying na.rm = TRUE to mean, sum or var.
The first set of examples illustrate reshaping: all the original variables are used.The first two examples show two ways to put the data back into its original form, with measured variables in the columns and all other id variables in the rows.The second and third examples are variations of this form where we put subject and then time in the columns.Because of the limitations of R data frames, it is not possible to label the columns and rows completely unambiguously.For example, note the last three examples where the data frame has no indication of the name of the variable that forms the columns.Additionally, some data values do not make valid column names, e.g., 'John Smith'.To use these within R, you often need to surround them with backticks, e.g., df$'John Smith'.The following examples demonstrate aggregation.Aggregation occurs when the combination of variables in the cast formula does not identify individual observations.In this case an aggregation function reduces the multiple values to a single one.See Section 4.4, page 11, for more details.These examples use the french fries dataset included in the reshape package.It is data from a sensory experiment on french fries, where different types of frier oil, treatment, were tested by different people, subject, over ten weeks time.The following casts show the different ways we can combine two variables: one each in row and column, both in row or both in column.When multiple variables appear in the column specification, their values are concatenated to form the column names.
~. R> ffm <-melt(french_fries, id = 1:4, na.rm = TRUE) It may take other arguments, passed in through ... in cast.Here are a few examples: You can also display margins and use functions that return multiple results.See the next two sections for details.

Table 1 :
These data are from a sensory experiment investigating the effect of different frying oils on the taste of French fries over time.There are three different types of frying oils (treatment), each in two different fryers (rep), tested by 12 people (subject) on 10 different days (time).The sensory attributes recorded, in order of desirability, are potato, buttery, grassy, rancid, painty flavours.The first few rows of the data are shown in Table1.First few rows of the French fries datasetWe first melt the data to use in subsequent analyses.One of the first things we might be interested in is how balanced this design is, and if there are many different missing values.We are interested in missingness, so we removed explicit missing values to put structural and non-structural missings on an equal footing.Each subject should have had 30 observations at each time, so by displaying the difference we can more easily see where the data are missing.
We can investigate balance using length as our aggregation function:R> cast(ffm, subject ~time, function(x) 30 -length(x), margins = TRUE)