Convert a vector into logical matrix

后端 未结 2 882
眼角桃花
眼角桃花 2021-01-26 03:00

Is there a native R function that will take an input vector and return the corresponding binary matrix where the matrix has the same number of columns as unique values in the in

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-26 03:12

    model.matrix() might help here, but you need to suppress the intercept:

    > model.matrix(~ factor(1:3) - 1)
      factor(1:3)1 factor(1:3)2 factor(1:3)3
    1            1            0            0
    2            0            1            0
    3            0            0            1
    attr(,"assign")
    [1] 1 1 1
    attr(,"contrasts")
    attr(,"contrasts")$`factor(1:3)`
    [1] "contr.treatment"
    

    Something slightly more complex:

    > set.seed(1)
    > fac <- factor(sample(1:3, 10, replace = TRUE))
    > model.matrix(~ fac - 1)
       fac1 fac2 fac3
    1     1    0    0
    2     0    1    0
    3     0    1    0
    4     0    0    1
    5     1    0    0
    6     0    0    1
    7     0    0    1
    8     0    1    0
    9     0    1    0
    10    1    0    0
    attr(,"assign")
    [1] 1 1 1
    attr(,"contrasts")
    attr(,"contrasts")$fac
    [1] "contr.treatment"
    

提交回复
热议问题