R: reshaping wide to long [duplicate]

与世无争的帅哥 提交于 2020-01-28 11:21:46

问题


I have a wide dataframe that looks something like this:

    ID Time Amount     CabMean CabNum     PartMean PartNum     DinnMean   DinNum  Ex
1    1    1    27  0.654621546      8           NA       7  0.316791872        6   0
2    1    2    82  0.667461321      3  0.327594876       4  0.346798127        2   1
3    1    3    52  0.313976132      1           NA       6  0.197837257        7   0
4    1    4    99  0.798328712      9  0.913751678       4  0.191679538        9   1

I would like to reshape (using the reshape2 package) it to a long format that takes this form (just making these numbers up):

  ID Time Amount Ex Type   Mean         Num
1  1    2    50   0  Cab   0.65654321   7
2  1    2    50   0 Part   0.65654321   1
3  1    2    50   0 Dinn   0.65654321   4

I have tried something like this:

reshaped <- melt(data, id.vars = c("ID", "Time", "Amount", "Ex"))

Which gets me something like this:

  ID Time Amount Ex  variable    value
1  1    1    10   0  CabMean 0.6565432
2  1    2    12   0  CabMean 0.6565432

So I'm only about half way there and can't quite figure out the rest. How do I (either from the code I'm currently using, or from completely new code) extract the type (Cab, Part, Dinn) as a separate column, and create 2 additional columns that hold Mean and Num values?


回答1:


We can use melt from data.table which can take multiple measure columns with the pattern argument. We convert the 'data.frame' to 'data.table' (setDT(data)), then melt to 'long' format.

library(data.table)
DT <- melt(setDT(data), measure=patterns('Mean$', 'Num$'), 
              variable.name='Type', value.name=c('Mean', 'Num'))
DT[, Type:=c('Cab', 'Part', 'Dinn')[Type]]


来源:https://stackoverflow.com/questions/34148392/r-reshaping-wide-to-long

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!