Convert numeric values into binary (0/1)

后端 未结 5 1574
余生分开走
余生分开走 2021-02-06 08:15

I have a data frame with counts of different kinds of fruits of different people. Like below

    apple  banana  orange
Tim     3       0       2
Tom     0                


        
5条回答
  •  北海茫月
    2021-02-06 09:13

    use can use ifelse. It should work on both matrix as well as dataframe however, resultant value will be matrix

    > df <- cbind(aaple = c(3, 0 , 1), banana = c(0, 1, 2), orange = c(2, 1, 2))
    > df
         aaple banana orange
    [1,]     3      0      2
    [2,]     0      1      1
    [3,]     1      2      2
    
    > ifelse(df>0, 1, 0)
         aaple banana orange
    [1,]     1      0      1
    [2,]     0      1      1
    [3,]     1      1      1
    

提交回复
热议问题