0

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.

Hack-R
  • 22,422
  • 14
  • 75
  • 131
  • could you please use `dput` to share the example vector? – Hack-R Jun 22 '16 at 14:06
  • 1
    Possible duplicate of [Recode categorical factor with N categories into N binary columns](http://stackoverflow.com/questions/16200241/recode-categorical-factor-with-n-categories-into-n-binary-columns) – Hack-R Jun 22 '16 at 14:10

1 Answers1

0
df <- read.table(file = "clipboard", sep = "\t", header=T)

df <-data.frame(variable= c("red","red","black","red","black","green",
        "black","red","green"))
df

  variable
1      red
2      red
3    black
4      red
5    black
6    green
7    black
8      red
9    green
class(df$variable)
[1] "factor"
model.matrix(~ . + 0, data=df, contrasts.arg = lapply(df, contrasts, contrasts=FALSE))

  variableblack variablegreen variablered
1             0             0           1
2             0             0           1
3             1             0           0
4             0             0           1
5             1             0           0
6             0             1           0
7             1             0           0
8             0             0           1
9             0             1           0
Hack-R
  • 22,422
  • 14
  • 75
  • 131