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

805 views Asked by At

I have a data frame of the following type

id  alphabet
20  a
20  b
30  b
30  c

now, there are multiple non-unique ids. there are multiple non-unique alphabets also.
i would like the result in the following format

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

so, rows have been combined based on unique id, and one-hot encoding has been done on the values (alphabets).
how can this be done on a large scale data frame?

1

There are 1 answers

3
Hardik Gupta On BEST ANSWER

You can use dcast like this

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