【问题标题】:Convert a factor to indicator variables? [duplicate]将因子转换为指标变量? [复制]
【发布时间】:2013-02-17 13:55:34
【问题描述】:

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

【问题讨论】:

标签: r


【解决方案1】:

一种方法是使用model.matrix():

model.matrix(~Species, iris)

    (Intercept) Speciesversicolor Speciesvirginica
1             1                 0                0
2             1                 0                0
3             1                 0                0

....

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"

【讨论】:

  • 我认为您必须在公式中添加-1,否则生成的矩阵中会缺少级别。
  • @juba 说得很好,但我认为这取决于您的目标。在虚拟编码中,您需要n-1 虚拟变量来表示n 变量。因此,在 iris$Species 示例中,00 的级别表示物种为 Setosa
  • @Andrien 你是对的,这取决于你想要得到的结果,没想到这个。
  • @Andrie 你知道一些标准的方法来扭转这种情况吗? IE。从给定的 model.matrix 中获取因子变量?
  • 如何将 model.matrix 输出合并回原始数据框?
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    如果我正确理解了您的问题,请使用model.matrix 命令,如下所示。

    dd <- data.frame(a = gl(3,4), b = gl(4,1,12))
    model.matrix(~ a + b, dd)
       (Intercept) a2 a3 b2 b3 b4
    1            1  0  0  0  0  0
    2            1  0  0  1  0  0
    3            1  0  0  0  1  0
    4            1  0  0  0  0  1
    5            1  1  0  0  0  0
    6            1  1  0  1  0  0
    7            1  1  0  0  1  0
    8            1  1  0  0  0  1
    9            1  0  1  0  0  0
    10           1  0  1  1  0  0
    11           1  0  1  0  1  0
    12           1  0  1  0  0  1
    attr(,"assign")
    [1] 0 1 1 2 2 2
    attr(,"contrasts")
    attr(,"contrasts")$a
    [1] "contr.treatment"
    
    attr(,"contrasts")$b
    [1] "contr.treatment"
    

    【讨论】:

      【解决方案4】:

      试试这个:

      myfactors<-factor(sample(c("f1","f2","f3"),10,replace=T));
      myIndicators<-diag(nlevels(myfactors))[myfactors,];
      

      【讨论】:

        猜你喜欢
        • 2017-03-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多