-1

I have some longitudinal data that looks like the following except with more subjects and times:

Date        Sub1  Sub2   Sub3 
8/10/2012   19.0  18.9   20.7 
8/13/2012   19.0  19.1   19.5 

I have dates at which each subject(sub1, sub2, and sub3) is given a score. How can I use reshape or any other R package to change this to the long format? so it looks like this:

Subject Score Date
Sub1    19.0  8/10/2012
Sub1    19.0  8/13/2012
Sub2    18.9  8/10/2012
Sub2    19.1  8/13/2012
Sub3    20.7  8/10/2012
Sub3    19.5  8/13/2012 
mnel
  • 113,303
  • 27
  • 265
  • 254
iantist
  • 833
  • 2
  • 12
  • 27

2 Answers2

1

Base R's reshape function also works fine for these types of problems, provided you know how to specify the inputs.

reshape(dat, direction = "long", 
        idvar = "Date", timevar = "Subject", 
        varying = 2:ncol(dat), sep = "")
#                  Date Subject  Sub
# 8/10/2012.1 8/10/2012       1 19.0
# 8/13/2012.1 8/13/2012       1 19.0
# 8/10/2012.2 8/10/2012       2 18.9
# 8/13/2012.2 8/13/2012       2 19.1
# 8/10/2012.3 8/10/2012       3 20.7
# 8/13/2012.3 8/13/2012       3 19.5
A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485
0

if your data is called dat

dat <- read.table(text="Date        Sub1  Sub2   Sub3 
                    8/10/2012   19.0  18.9   20.7 
                    8/13/2012   19.0  19.1   19.5 ",header=TRUE)

  library(reshape2)
  melt(dat)

  # explicitly you would use Date as AN id
  # melt(dat, id = "Date")
user1317221_G
  • 15,087
  • 3
  • 52
  • 78
  • Thanks that worked great. I've been confused about when to use reshape() vs melt(). I was trying to use reshape because I had seen it used before with longitudinal data to convert wide to long and vice versa. – iantist Feb 07 '13 at 21:34
  • @iantist, see [my answer](http://stackoverflow.com/a/14765994/1270695) for how to do this in base R reshape. Also, to avoid downvotes on your questions in the future, do be sure to at least provide an indication of the code you have tried. – A5C1D2H2I1M1N2O1R2T1 Feb 08 '13 at 05:05