wide to long multiple measures each time
This is pretty close and changing the names of columns should be within your skillset:
reshape(DF,
varying=c(work= c(3, 7), play= c(4,8), talk= c(5,9), total= c(6,10) ),
direction="long")
EDIT: Adding a version that is almost an exact solution:
reshape(DF, varying=list(work= c(3, 7), play= c(4,8), talk= c(5,9), total= c(6,10) ),
v.names=c("Work", "Play", "Talk", "Total"),
# that was needed after changed 'varying' arg to a list to allow 'times'
direction="long",
times=1:2, # substitutes number for T1 and T2
timevar="times") # to name the time col
The most concise way is to use tidyr combined with dplyr library.
library(tidyr)
library(dplyr)
result <- DF %>%
# transfer to 'long' format
gather(loc, value, work.T1:total.T2) %>%
# separate the column into location and time
separate(loc, into = c('loc', 'time'), '\\.') %>%
# transfer to 'short' format
spread(loc, value) %>%
mutate(time = as.numeric(substr(time, 2, 2))) %>%
arrange(time)
tidyr is designed specifically to make data tidy.
Oddly enough I don't seem to get the same numbers as you (which I should since we both used set.seed(10)
?) but otherwise this seems to do the trick:
library(reshape) #this might work with reshape2 as well, I haven't tried ...
DF2 <- melt(DF,id.vars=1:2)
## split 'activity.time' label into two separate variables
DF3 <- cbind(DF2,
colsplit(as.character(DF2$variable),"\\.",
names=c("activity","time")))
## rename time, reorder factors:
DF4 <- transform(DF3,
time=as.numeric(gsub("^T","",time)),
activity=factor(activity,
levels=c("work","play","talk","total")),
id=factor(id,levels=paste("x1",1:10,sep=".")))
## reshape back to wide
DF5 <- cast(subset(DF4,select=-variable),id+trt+time~activity)
## reorder
DF6 <- with(DF5,DF5[order(time,id),])
It's more complicated than @DWin's answer but maybe (?) more general.