Reshaping 2 column data.table from long to wide

2019-09-10 06:04发布

问题:

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