'Convert categorical variable into binary columns in R [duplicate]

I made the stupid mistake of enabling people to select multiple categories in a survey question.

Now the data column for this question looks something along the lines of this.

respondent answer_openq
1 a
2 a,c
3 b
4 a,d

using the following line in r,

datanum <- data %>% mutate(dummy=1) %>%
spread(key=answer_openq,value=dummy, fill=0)

I get the following: data how it looks like now

However, I want the dataset to transform into this:

respondent a b c d
1 1 0 0 0
2 1 0 1 0
3 0 1 0 0
4 1 0 0 1

Any help is appreciated (my thesis depends on it). Thanks :)



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source