Skip to main content

Reshaping Data in R

R provides a variety of methods for reshaping data prior to analysis.

Transpose

Use the t() function to transpose a matrix or a data frame. In the later case, rownames become variable (column) names.

# example using built-in dataset
mtcars
t(mtcars)

The Reshape Package

Hadley Wickham has created a comprehensive package called reshape to massage data. Both an introduction and article are available. There is even a video!

Basically, you "melt" data so that each row is a unique id-variable combination. Then you "cast" the melted data into any shape you would like. Here is a very simple example.

mydata

    
idtimex1x2
1156
1235
2161
2224
# example of melt function
library(reshape)
mdata <- melt(mydata, id=c("id","time"))

newdata

    
idtimevariablevalue
11x15
12x13
21x16
22x12
11x26
12x25
21x21
22x24
# cast the melted data
# cast(data, formula, function)
subjmeans <- cast(mdata, id~variable, mean)
timemeans <- cast(mdata, time~variable, mean)

subjmeans

   
idx1x2
145.5
242.5

timemeans

   
timex1x2
15.53.5
22.54.5

There is much more that you can do with the melt( ) and cast( ) functions. See the documentation for more details.

Going Further

To practice massaging data, try this course in cleaning data in R.