I have a data like below and i want to convert this variable into columns which should be equal to no.of classes in a varible.
data :
variable
1 red
2 red
3 black
4 red
5 black
6 green
7 black
8 red
9 green
expected output :
variable red black green
1 red 1 0 0
2 red 1 0 0
3 black 0 1 0
4 red 1 0 0
5 black 0 1 0
6 green 0 0 1
7 black 0 1 0
8 red 1 0 0
9 green 0 0 1
Tried :
data$red = ifelse(data$variable == "red",1,0)
data$black = ifelse(data$variable == "black",1,0)
data$green = ifelse(data$variable == "green",1,0)
By using above code, I achieved what I want. But if I have more than 10 classes in a variable, I don't want to write the code for 10 times. So, is there any best way to do this in one go.