Search code examples
rcategorical-datar-factordummy-variablennet

What does R's class.ind() function do and when would I use it?


R documentation says that nnet::class.ind() generates a class indicator function from a given factor.

Does it convert a factor to some binary classification?

When and why do we use this function? Please give me some examples.

Any help appreciated. Thank you.


Solution

  • Yes. It creates indicator/dummy variables from a factor:

    > set.seed(1)
    > x <- factor(sample(1:3, 10, TRUE))
    > nnet::class.ind(x)
          1 2 3
     [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
    

    It would be essentially the same as using model.matrix:

    > model.matrix(~0+x)
       x1 x2 x3
    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