Reshaping 2 column data.table from long to wide

送分小仙女□ 提交于 2020-01-16 19:37:09

问题


This is my data.frame:

library(data.table)
    df<- fread('

predictions Label
   3           A
   4           B
   5           C
   1           A
   2           B
   3           C
')

Desired Output:

A  B  C
3  4  5
1  2  3

I am trying DesiredOutput<-dcast(df, Label+predictions ~ Label, value.var = "predictions") with no success. Your help is appreciated!


回答1:


Maybe the base R function unstack is the cleanest solution:

unstack(df)
  A B C
1 3 4 5
2 1 2 3

Note that this returns a data.frame rather than a data.table, so if you want a data.table at the end:

df2 <- setDT(unstack(df))

will return a data.table.




回答2:


df[, idx := 1:.N, by = Label]

dcast(df, idx ~ Label, value.var = 'predictions')
#   idx A B C
#1:   1 3 4 5
#2:   2 1 2 3


来源:https://stackoverflow.com/questions/38333560/reshaping-2-column-data-table-from-long-to-wide

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