Converting multiple boolean columns to single factor column

后端 未结 4 391
伪装坚强ぢ
伪装坚强ぢ 2020-12-12 03:02

my data frame look like this:

      A S1 S2 S3 S4
1   ex1  1  0  0  0
2   ex2  0  1  0  0
3   ex3  0  0  1  0
4   ex4  1  0  0  0
5   ex5  0  0  0  1
6   ex6         


        
4条回答
  •  心在旅途
    2020-12-12 03:41

    You can use apply and check the max in the columns 2-5 and then return the corresponding column name:

    df$Type <- apply(df[2:5], 1, function(x) names(df)[which.max(x)+1] )
    

    Afterwards, you can delete the columns you don't need anymore:

    df <- df[,-c(2:5)]
    

提交回复
热议问题