-2

I have trouble reshaping a data frame.

Here is a sample data set:

u<-data.frame(patient=1:9,time=1:3,var1=rnorm(9),var2=rnorm(9),var3=rnorm(9),var5=rnorm(9),var6=rnorm(9))

Instead of 6, I have 20 variables.

This only thing I want, is to make this wide data set into a long data set. Also, I have been searching on Stack Overflow/Google how to do this, but unsuccessful. Most reshape questions posted here seem way more difficult then what I am after.

What I am after is:

patient time    variable    value
1          1    var1        1.70484636
2          2    var1        0.19637999
3          3    var1        -1.20419038
4          1    var1        0.06944788
5          2    var1        -1.03074549
6          3    var1        0.9396862
7          1    var1        -0.57904879
8          2    var1        1.16163798
9          3    var1        1.11314472
1          1    var2        0.2138141
2          2    var2        2.9763986
3          3    var2        0.9686543
4          1    var2        0.1321531
5          2    var2        0.844687
6          3    var2        1.1336502
7          1    var2        0.5902222
8          2    var2        1.392971
9          3    var2        1.5335116
1          1    var3        0.93968 62
2          2    var3        2.9763986
3          3    var3        0.844687
....
Nimantha
  • 6,405
  • 6
  • 28
  • 69
Luc
  • 899
  • 11
  • 26

2 Answers2

1

Did you come across the reshape2 package on your stackoverflow/Google search?

require(reshape2)
melt(u, id = c('patient', 'time'))
#   patient time variable       value
1        1    1     var1  0.25585248
2        2    2     var1 -0.98750355
3        3    3     var1 -0.12871163
4        4    1     var1 -0.11789488
5        5    2     var1 -1.16252583
6        6    3     var1 -0.46498923
7        7    1     var1 -2.11571402
8        8    2     var1 -1.91485293
9        9    3     var1 -0.19154752
10       1    1     var2  2.38927206
[skip]
EDi
  • 13,160
  • 2
  • 48
  • 57
0

You're looking for the reshape2 package.

require('reshape2')
head(melted.u <- melt(u, id.vars=c('patient', 'time')))

  patient time variable   value
1       1    1     var1 -1.8745
2       2    2     var1  0.6428
3       3    3     var1  0.4367
4       4    1     var1  0.1102
5       5    2     var1 -0.1590
6       6    3     var1  1.7786
N8TRO
  • 3,348
  • 3
  • 22
  • 40