My data has several categorical features with multiple labels (multilabel) per record spread over multiple rows.
myDf <- data.frame(myGroup = c("A", "B", "B", "C", "C", "C"),
myFruit = as.factor(c("apple", "apple", "banana", "apple", "lime", "lemon")),
myCode = as.factor(c("AAA", "AAA", "CCC", "AAA", "BBB", "CCC")))
myDf
myGroup myFruit myCode
A apple AAA
B apple AAA
B banana CCC
C apple AAA
C lime BBB
C lemon CCC
The expected output would look like:
myGroup apple banana lemon lime AAA BBB CCC
A 1 0 0 0 1 0 0
B 1 1 0 0 1 0 1
C 1 0 1 1 1 1 1
How can I one-hot encode this multi label data?
I am including a self-answer, however I suspect there is a better way to do this.
For example. there are 20 fields in need of encoding, should I use repeat mutate/spread 20 times?