One option is one of the other Hadley packages: reshape2 :
> require(reshape2) > dat patient analyte1 analyte2 analyte3 1 pt1 1 3 5 2 pt2 2 6 7 3 pt3 9 10 2 > melt(dat, id = "patient") patient variable value 1 pt1 analyte1 1 2 pt2 analyte1 2 3 pt3 analyte1 9 4 pt1 analyte2 3 5 pt2 analyte2 6 6 pt3 analyte2 10 7 pt1 analyte3 5 8 pt2 analyte3 7 9 pt3 analyte3 2 > str(melt(dat, id = "patient")) 'data.frame': 9 obs. of 3 variables: $ patient : Factor w/ 3 levels "pt1","pt2","pt3": 1 2 3 1 2 3 1 2 3 $ variable: Factor w/ 3 levels "analyte1","analyte2",..: 1 1 1 2 2 2 3 3 3 $ value : int 1 2 9 3 6 10 5 7 2
You can do this in a longer way using reshape() from the R base:
reshape(dat, direction = "long", sep = "", varying = 2:4, times = names(dat)[2:4], idvar = "patient", timevar = "variable", v.names = "value")
and the main difference is that variable not a factor with the reshape() base. I suppose this is a user reshape2 , it was the motivation for writing reshape2 ...
source share