将因子转换为指标变量?

Moh*_*Aly 3 r

如何将R中的因子转换为多个指标变量,每个级别一个?

And*_*rie 8

一种方法是使用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)


jub*_*uba 5

有几种方法可以做到,但您可以使用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)