Convert categorical column to multiple binary colu

2019-09-22 04:37发布

This question already has an answer here:

I would like to convert this column into binary columns for each breed (1 dog is breed, 0 dog is not that breed)

enter image description here

标签: r tidyr
2条回答
混吃等死
2楼-- · 2019-09-22 05:18

Use model.matrix() to convert your categorical variable in binary variables.

Breed = c(
  "Sheetland Sheepdog Mix",
  "Pit Bull Mix",
  "Lhasa Aposo/Miniature",
  "Cairn Terrier/Chihuahua Mix",
  "American Pitbull",
  "Cairn Terrier",
  "Pit Bull Mix"
)
df=data.frame(Breed)

dfcat = data.frame(model.matrix(~ df$Breed-1, data=df))
names(dfcat) = levels(df$Breed)

So dfcat contains your binary variables:

dfcat
#American Pitbull Cairn Terrier Cairn Terrier/Chihuahua Mix Lhasa Aposo/Miniature Pit Bull Mix Sheetland Sheepdog Mix
#              0             0                           0                     0            0                      1
#              0             0                           0                     0            1                      0
#              0             0                           0                     1            0                      0
#              0             0                           1                     0            0                      0
#              1             0                           0                     0            0                      0
#              0             1                           0                     0            0                      0
#              0             0                           0                     0            1                      0
查看更多
SAY GOODBYE
3楼-- · 2019-09-22 05:27

One way could be using unique with a for-loop

Breed = c(
  "Sheetland Sheepdog Mix",
  "Pit Bull Mix",
  "Lhasa Aposo/Miniature",
  "Cairn Terrier/Chihuahua Mix",
  "American Pitbull",
  "Cairn Terrier",
  "Pit Bull Mix"
)
df=data.frame(Breed)

for (i in unique(df$breed)){
  df[,paste0(i)]=ifelse(df$Breed==i,1,0)
}
查看更多
登录 后发表回答