-1

I want to reshape my data frame from the df1 to df2 as appears below:

df1 <-

ID  TIME  RATEALL  CL  V1  Q  V2
1    0      0      2.4 10  6  20
1    1      2      0.6 10  6  25
2    0      0      3.0 15  7  30
2    5      3      3.0 16  8  15

into a long format like this:

df2 <- 

ID  var  TIME  value
 1   1    0     0
 1   1    1     2
 1   2    0     2.4
 1   2    1     10
 1   3    0     6
 1   3    1     6
 1   4    0     20
 1   4    1     20 
 2   1    0     3.0
 2   1    1     3.0
 AND so on ...

Basically I want to give a flag variables (1: for RATEALL, 2:for CL, 3:for V1, 4:for Q,and 5: for V2 and then melt the values for each subject ID. Is there an easy way to do this in R?

Jaap
  • 81,064
  • 34
  • 182
  • 193
Amer
  • 2,131
  • 3
  • 23
  • 38
  • In your expected outcome, I would expect 10 rows for ID1. I wonder if you happened to miss some parts of the data or if you purposely deleted them. – jazzurro Feb 12 '15 at 02:29
  • I didn't make df2 in full. I wanted only to show the principle. – Amer Feb 12 '15 at 02:50
  • I see. I just wanted to make sure what you wanted before I post an answer. – jazzurro Feb 12 '15 at 02:52

2 Answers2

1

You can try

df2 <- reshape2::melt(df1, c("ID", "TIME"))
names <- c("RATEALL"=1, "CL"=2, "V1"=3, "Q"=4, "V2"=5)
df2$variable <- names[df2$variable]
Khashaa
  • 7,293
  • 2
  • 21
  • 37
1

You could use tidyr/dplyr

library(tidyr)
library(dplyr)
res <- gather(df1,var, value, RATEALL:V2) %>% 
             mutate(var= as.numeric(factor(var)))
head(res)
#  ID TIME var value
#1  1    0   1   0.0
#2  1    1   1   2.0
#3  2    0   1   0.0
#4  2    5   1   3.0
#5  1    0   2   2.4
#6  1    1   2   0.6
akrun
  • 874,273
  • 37
  • 540
  • 662