Convert categorical column to multiple binary columns [duplicate]

穿精又带淫゛_ 提交于 2019-12-13 09:54:00

问题


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


回答1:


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)
}



回答2:


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


来源:https://stackoverflow.com/questions/44747961/convert-categorical-column-to-multiple-binary-columns

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!