2016-07-12 30 views
0

这是我的data.frame:重塑2列data.table从长到宽

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

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

所需的输出:

A B C 
3 4 5 
1 2 3 

我想DesiredOutput<-dcast(df, Label+predictions ~ Label, value.var = "predictions")没有成功。感谢您的帮助!

回答

2

或许基础R功能unstack是干净的解决方案:

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

注意,这个返回data.frame而非data.table,所以如果你想在最后一个data.table:

df2 <- setDT(unstack(df)) 

将返回一个data.table。

4
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 
+2

或'dcast(df,rowid(Label)〜Label,value.var ='predictions')',我想。 – Frank