Converting R Factors into Binary Matrix Values

前端 未结 3 416
猫巷女王i
猫巷女王i 2021-02-01 09:02

I would like to convert my dataframe into a matrix that expands a single factor column into multiple ones and assigns a 1/0 depending on the factor. Fo

3条回答
  •  后悔当初
    2021-02-01 09:36

    Assuming dat is your data frame:

    cbind(dat, model.matrix( ~ 0 + C1, dat))
    
      C1 C2 C3 C1A C1B
    1  A  3  5   1   0
    2  B  3  4   0   1
    3  A  1  1   1   0
    

    This solution works with any number of factor levels and without manually specifying column names.

    If you want to exclude the column C1, you could use this command:

    cbind(dat[-1], model.matrix( ~ 0 + C1, dat))
    

提交回复
热议问题