一种具有多个 ID、大型数据帧中的值的热编码

One hot encoding with multiple ids, values in a large dataframe

我有以下类型的数据框

id  alphabet
20  a
20  b
30  b
30  c

现在,有多个非唯一 ID。还有多个非唯一字母表。
我想要以下格式的结果

id  alphabet_a  alphabet_b  alphabet_c
    20  1           1         0
    30  0           1         1

因此,已根据唯一 ID 组合行,并对值(字母)进行了单热编码。
这如何在大规模数据框架上完成?

你可以这样使用dcast

library(reshape2)

df <- read.table(text = "id  alphabet
             20  a
             20  b
             30  b
             30  c", header = T)

dcast(df, id~alphabet, fun = length)

  id a b c
1 20 1 1 0
2 30 0 1 1