Converting R Factors into Binary Matrix Values

前端 未结 3 414
猫巷女王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:51

    dat <- read.table(text =' C1 C2 C3
    A  3  5
    B  3  4
    A  1  1',header=T)
    

    Using transform

    transform(dat,C1_A =ifelse(C1=='A',1,0),C1_B =ifelse(C1=='B',1,0))[,-1]
      C2 C3 C1_A C1_B
    1  3  5    1    0
    2  3  4    0    1
    3  1  1    1    0
    

    Or to get more flexbility , with within

    within(dat,{ 
                 C1_A =ifelse(C1=='A',1,0)
                 C1_B =ifelse(C1=='B',1,0)})
    
      C1 C2 C3  C1_B C1_A
    1  A  3  5    0    1
    2  B  3  4    1    0
    3  A  1  1    0    1
    

提交回复
热议问题