Home » Analytics » Using Reshape2 for transposing datasets in R

Using Reshape2 for transposing datasets in R

Software

R in the Cloud

Train in R

Note Problem Statement-This is quite similar to using Proc Transpose using values in SAS. see http://analytics.ncsu.edu/sesug/2005/TU12_05.PDF
Diagram using geneplotter from R Graph Gallery
In R however this can be done as follow.
convert dataframe
Subject     Item      Score
1 Subject 1     Item 1     1
2 Subject 1     Item 2     0
3 Subject 1     Item 3     1
4 Subject 2     Item 1     1
5 Subject 2     Item 2     1
6 Subject 2      Item 3     0
to
Subject     Item 1 Item 2 Item 3 Item 4
1 Subject 1      1              0               1                 1
5 Subject 2      1              1                0                0
Note- I am using http://www.inside-r.org/pretty-r/tool for auto-generating the color coded R Code.
library("reshape2")
tDat.m<- melt(tDat)tDatCast<- acast(tDat.m,Subject~Item)
and that's it!
Another way (this one is  not recommended as it seems to take longer
 and more memory)
df.wide <- reshape(df, idvar="Subject", timevar="Item", direction="wide")

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Conferences

Predictive Analytics- The Book

Books

Follow

Get every new post delivered to your Inbox.

Join 840 other followers