Long to wide w/ two repeated measures

前端 未结 2 2078
無奈伤痛
無奈伤痛 2021-01-02 03:35

I know this has been asked numerous times on here under the rubric of \"long to wide\" but I\'ve run into a situation where I have two value variables that are repeated meas

相关标签:
2条回答
  • 2021-01-02 03:40

    Ben's answer is great considering the date this question was asked. However, it should be noted that the dcast function included in more recent versions of "data.table" can handle problems like this without having to first melt the data. As such, it would be a more efficient approach to use.

    library(data.table)
    dcast(as.data.table(DF), id + sex ~ time, value.var = c("score1", "score2"))
    ##           id sex score1_Time1 score1_Time2 score1_Time3 score2_Time1 score2_Time2 score2_Time3
    ## 1: subject 1   m   0.78213630   -0.1557955  -0.10278773    1.5771598     1.013447    1.4583278
    ## 2: subject 2   m   0.07456498   -1.4707524   0.38767161    0.2372536     2.787854    3.0741317
    ## 3: subject 3   m  -1.98935170   -0.4781501  -0.05380504    4.4001015     2.226653    0.4493848
    ## 4: subject 4   f   0.61982575    0.4179416  -1.37705956    3.0527030     2.755023    3.5244309
    ## 5: subject 5   f  -0.05612874    1.3586796  -0.41499456    0.6580944     2.829981    1.5924235
    
    0 讨论(0)
  • 2021-01-02 04:02

    I think this will do it:

    library(reshape)
    m <- melt(DF)
    

    Simplest, but time and score are in the opposite order from your example (in case it matters)

    cast(m,id+sex~...)
    

    Or more explicitly:

    cast(m,id+sex~variable+time)
    

    You can cut this down to a one-liner:

    recast(DF,id+sex~...)
    

    If you like you can use the newer reshape2 package instead of reshape, replacing cast with dcast (the version of recast included in reshape2 doesn't give the desired result.)

    0 讨论(0)
提交回复
热议问题