一种方法是使用model.matrix():
model.matrix(~Species, iris)
(Intercept) Speciesversicolor Speciesvirginica
1 1 0 0
2 1 0 0
3 1 0 0
Run Code Online (Sandbox Code Playgroud)
....
148 1 0 1
149 1 0 1
150 1 0 1
attr(,"assign")
[1] 0 1 1
attr(,"contrasts")
attr(,"contrasts")$Species
[1] "contr.treatment"
Run Code Online (Sandbox Code Playgroud)
有几种方法可以做到,但您可以使用model.matrix:
color <- factor(c("red","green","red","blue"))
data.frame(model.matrix(~color-1))
# colorblue colorgreen colorred
# 1 0 0 1
# 2 0 1 0
# 3 0 0 1
# 4 1 0 0
Run Code Online (Sandbox Code Playgroud)