This question already has an answer here:
- Generate a dummy-variable 15 answers
I would like to convert this column into binary columns for each breed (1 dog is breed, 0 dog is not that breed)
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)
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)
}
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