Converting multiple boolean columns to single factor column

后端 未结 4 375
伪装坚强ぢ
伪装坚强ぢ 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:34

    Could also do (if dat is your data set)

    library(reshape2)
    dat <- melt(dat, id = "A")
    dat[dat$value > 0, 1:2]
    
    0 讨论(0)
  • 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)]
    
    0 讨论(0)
  • 2020-12-12 03:45

    You could try: If df is the dataframe

    data.frame(A=df$A, Type=rep(names(df)[-1], nrow(df))[!!t(df[,-1])])
        A Type
    1   ex1   S1
    2   ex2   S2
    3   ex3   S3
    4   ex4   S1
    5   ex5   S4
    6   ex6   S2
    7   ex7   S1
    8   ex8   S2
    9   ex9   S3
    10 ex10   S1
    

    Also:

       names(df)[-1][t(df[-1])*seq_len(ncol(df)-1)]
     [1] "S1" "S2" "S3" "S1" "S4" "S2" "S1" "S2" "S3" "S1"
    
    0 讨论(0)
  • 2020-12-12 03:48

    Assuming d is the data, the new column could be obtained with

    d$type <- names(d[-1])[apply(d[-1] == 1, 1, which)]
    d[c(1, 6)]
    #       A type
    # 1   ex1   S1
    # 2   ex2   S2
    # 3   ex3   S3
    # 4   ex4   S1
    # 5   ex5   S4
    # 6   ex6   S2
    # 7   ex7   S1
    # 8   ex8   S2
    # 9   ex9   S3
    # 10 ex10   S1
    
    0 讨论(0)
提交回复
热议问题