wide to long multiple measures each time

后端 未结 5 1367
慢半拍i
慢半拍i 2020-12-01 06:45

I know the wide to long has been asked way too many times on here but I can\'t figure out how to turn the following into long format. Shoot I even asked one of the wide to

5条回答
  •  暖寄归人
    2020-12-01 07:19

    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.

提交回复
热议问题