Reshaping multiple sets of measurement columns (wide format) into single columns (long format)
reshape(dat, idvar="ID", direction="long",
varying=list(Start=c(2,5,8), End=c(3,6,9), Value=c(4,7,10)),
v.names = c("DateRangeStart", "DateRangeEnd", "Value") )
#-------------
ID time DateRangeStart DateRangeEnd Value
1.1 1 1 1/1/90 3/1/90 4.4
1.2 1 2 4/5/91 6/7/91 6.2
1.3 1 3 5/5/95 6/6/96 3.3
(Added the v.names per Josh's suggestion.)
data.table
's melt
function can melt into multiple columns. Using that, we can simply do:
require(data.table)
melt(setDT(dat), id=1L,
measure=patterns("Start$", "End$", "^Value"),
value.name=c("DateRangeStart", "DateRangeEnd", "Value"))
# ID variable DateRangeStart DateRangeEnd Value
# 1: 1 1 1/1/90 3/1/90 4.4
# 2: 1 2 4/5/91 6/7/91 6.2
# 3: 1 3 5/5/95 6/6/96 3.3
Alternatively, you can also reference the three sets of measure columns by the column position:
melt(setDT(dat), id = 1L,
measure = list(c(2,5,8), c(3,6,9), c(4,7,10)),
value.name = c("DateRangeStart", "DateRangeEnd", "Value"))